- 2.17
- 秒了
class Solution {
public int maxProfit(int[] prices) {
int minIn = Integer.MAX_VALUE;
int maxp = Integer.MIN_VALUE;
for(int i=0;i<prices.length;i++){
minIn = Math.min(minIn,prices[i]);
maxp = Math.max(maxp,prices[i]-minIn);
}
return maxp;
}
}- 2.3
- 用了两个 for 循环,时间超,应该记录全局最小值,一个 for 就够用
就是记录最大利润和最小价格
- 12.1
- 关键点:最低价格和最大利润,上面说的对
class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for(int i=0;i<prices.length;i++){
if(prices[i]<minPrice){
minPrice = prices[i];
}else if(prices[i]-minPrice > maxProfit){
maxProfit = prices[i]-minPrice;
}
}
return maxProfit;
}
}