題目: LeetCode - 121. Best Time to Buy and Sell Stock

題目說明

給一個陣列代表每日的股票價格,求買賣一次的最大收益。

解題思路

動態規劃,轉移方程為:

1
2
cost = min(p, cost);
profit = max(p - cost, profit);

參考解法

1
2
3
4
5
6
7
8
class Solution {
public:
int maxProfit(vector<int>& prices) {
int cost = INT_MAX, profit = 0;
for(auto p : prices) cost = min(p, cost), profit = max(p - cost, profit);
return profit;
}
};