week15-leetcode #122-BestTimetoBuyandSellStock II
链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
Question
Say you have an array for which the i i th element is the price of a given stock on day .
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Example
Input: [7, 1, 5, 3, 6, 4]
Output: 7
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
Solution
class Solution {
public:
int maxProfit(vector<int>& prices) {
int size = prices.size();
if (size == 0) return 0;
int *max_profit = new int[size];
for (int i = 0; i < size; i++) max_profit[i] = 0;
int start_index = 0;
int min_val = prices[0];
max_profit[0] = 0;
for (int i = 1; i < size-1; i++) {
min_val = (min_val < prices[i]) ? min_val: prices[i];
if (prices[i] > prices[i+1]) {
max_profit[i] = max_profit[i-1] + prices[i]-min_val;
start_index = i+1;
min_val = prices[start_index];
} else {
max_profit[i] = max_profit[i-1];
}
}
if (prices[size-1] - min_val >= 0) {
max_profit[size-1] = max_profit[size-2] + prices[size-1] - min_val;
} else {
max_profit[size-1] = max_profit[size-2];
}
return max_profit[size-1];
}
};
思路: min_val m i n _ v a l 是从上次计算 profit p r o f i t 得到的 start s t a r t 到 i i 为止的最小值,遍历一遍prices数组,当大于 prices[i+1] p r i c e s [ i + 1 ] 的时候,计算这时产生的 profit=prices[i]−min_val p r o f i t = p r i c e s [ i ] − m i n _ v a l 。最大利益即使将这些 profit p r o f i t 累加起来。