【leetcode】121.(Easy)Best Time to Buy and Sell Stock

解题思路:

方法一:滑动窗口

时间复杂度:O(n)

方法二:迭代更新

每当有更低价时更新买价,
每当有更高价时更新卖价,
期间更新每一次的买价和卖价的差价

另一方面,为了避免用“今天的低价”购买“昨天的高价”,在有更低价时同时更新买价和卖价(继而当天的买卖差价为0)

最后就变成了:
每当有更低价时同时更新买价和卖价
每当有更高价时更新卖价,
期间更新每一次的买价和卖价的差价

时间复杂度:O(n)


提交代码:滑动窗口

class Solution{
	public int maxProfit(int[] prices) {
		int curMax=0,res=0;
		for(int  i=1;i<prices.length;i++) {
			curMax=Math.max(0, curMax+prices[i]-prices[i-1]);
			res=Math.max(res, curMax);
		}
		return res;
	}
}

运行结果:
在这里插入图片描述


提交代码:基础迭代

class Solution{
	public int maxProfit(int[] prices) {
		int res=0,min=Integer.MAX_VALUE,max=Integer.MAX_VALUE;
		for(int price : prices) {
			if(price<min) {
				min=price;max=price;
			}else if(price>max){
					max=price;
					res=Math.max(res, max-min);
				}
		}
		return res;
	}
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/AXIMI/article/details/85525337
今日推荐