public class Solution {
public int maxProfit(int prices[]) {
int maxProfit = 0; //记录当前可以获得的最大利润
int length = prices.length; //获取价格数组长度
for (int i = 0; i < length-1; i++) {
for (int j = i + 1; j < prices.length; j++) {
if (prices[j] - prices[i]> maxProfit) {
maxProfit = prices[j] - prices[i]; //更新最大利润
}
}
}
return maxProfit;
}
}
思路2
class Solution {
public int maxProfit(int[] prices) {
if(prices.length <= 1){
return 0;
}
int maxProfit = 0;
int minPrice = prices[0]; //记录当前历史最低点
for(int i=1; i<prices.length; i++){
if(prices[i]<minPrice){
minPrice = prices[i]; //更新历史最低点
}else if(prices[i] - minPrice > maxProfit){
maxProfit = prices[i] - minPrice; //更新最大利润
}
}
return maxProfit;
}
}