LeetCode121 Best Time to Buy and Sell Stock

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

样例

1
2
3
4
5
Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6,
as selling price needs to be larger than buying price)
1
2
3
4
Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

思路

给出$N$天的股价,在只能做一次交易的情况下,问最大收益是多少。

考虑第$i$天卖出的最大收益,其实就是等于第$i$天的价格减去前$i-1$天的最低价格,即 ,那么只要维护一个当前最小值就好了。

代码

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int maxProfit(vector<int>& prices) {
int ans = 0, curMin = INT_MAX;
for (int& x: prices) {
ans = max(ans, x - curMin);
curMin = min(curMin, x);
}
return ans;
}
};
分享到 评论