思路
第一个确定是buyVal
第二个三种情况
- 大于等于buyVal,就把这个设置为saleVal
- 小于buyVal buyVal 改变为这个,继续遍历
错误思路
我的想法是:先把买的时机确定了,再确定卖的时机,分类讨论,实际操作过程中,有问题:就是它总是改变的这样设计的话,最好是拥有一个不变的
正确思路
把这个数组分为左右两部分,右边最大值减去左边最小值
1+9
2+8
3+7
……
4+6
9+1
class Solution {
public:
int maxProfit(vector<int>& prices) {
int inf = 1e9;
int minprice = inf, maxprofit = 0;
for (int price: prices) {
maxprofit = max(maxprofit, price - minprice);
minprice = min(price, minprice);
}
return maxprofit;
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/solution/121-mai-mai-gu-piao-de-zui-jia-shi-ji-by-leetcode-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
我的
class Solution {
public:
int maxProfit(vector<int>& prices) {
int maxProfit = 0;
int leftMin = prices[0];
for(int i=1;i<prices.size();i++){
if(prices[i] < leftMin){
leftMin = prices[i];
}
maxProfit = max(maxProfit,prices[i] - leftMin);
}
return maxProfit;
}
};