121. 买卖股票的最佳时机
121. 买卖股票的最佳时机
简单题,很容易想到 O(n2)的代码:
public int maxProfit(int[] prices) {
int res = 0;
for(int i = 0; i< prices.length;i++){
for(int j = i+1; j<prices.length;j++){
res = Math.max(res,prices[j] - prices[i]);
}
}
return res;
}
但是这样会超时,
public int maxProfit(int[] prices) {
if(prices == null) return 0;
int[] maxs = new int[prices.length];
int res = 0;
//记录前i-1天最小值
int minLastI = prices[0];
for(int i = 1; i< prices.length;i++){
maxs[i] = Math.max(maxs[i-1],prices[i] - minLastI);
if(prices[i] < minLastI){
minLastI = prices[i];
}
}
return maxs[prices.length-1];
}
可以考虑继续优化空间
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;
}
本作品采用知识共享署名 4.0 国际许可协议进行许可。转载请注明出处:landery个人学习分享
评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果