week14-leetcode #121-BestTimetoBuyandSellStock
链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
Question
Say you have an array for which the ith i t h element is the price of a given stock on day i 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.
Example
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)
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
Solution1 — 非DP
class Solution {
public:
int maxProfit(vector<int>& prices) {
int min_val = 999999;
int max_diff = 0;
for (int i = 0; i < prices.size(); i++) {
min_val = (min_val > prices[i]) ? prices[i]: min_val;
max_diff = (max_diff < prices[i]-min_val) ? (prices[i]-min_val) : max_diff;
}
return max_diff;
}
};
思路:遍历一次prices数组,到位置的时候记录下当前时刻的最小值是多少,求出当前为止最大的利润。
Solution2 — DP
class Solution {
public:
int maxProfit(vector<int>& prices) {
int size = prices.size();
int *max_profit = new int[size];
int *min_val = new int[size];
min_val[0] = prices[0];
max_profit[0] = 0;
for (int i = 1; i < size; i++) {
min_val[i] = min(min_val[i-1], prices[i]);
max_profit[i] = max(max_profit[i-1], prices[i]-min_val[i]);
}
return max_profit[size-1];
}
};
思路:
max_profit[i]
m
a
x
_
p
r
o
f
i
t
[
i
]
表示到位置
i
i
为止的最大利润,转移方程是:
初始化
max_profit[i]=max(max_profit[i−1],prices[i]−min_val[i]) m a x _ p r o f i t [ i ] = m a x ( m a x _ p r o f i t [ i − 1 ] , p r i c e s [ i ] − m i n _ v a l [ i ] )