[Leetcode 51] 122 Best Time to Buy and Sell Stock II
Problem:
Say you have an array for which the ith element is the price of a given stock on day i.
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).
Analysis:
As we mentioned in "Best Time to Buy and Sell Stock" problem, every day make a transaction can get the knowledge of how much profit you can have on every day. Since here we are allowed to make as many transactions as we like, we just need to make those transactions with profit and ignore others. Then we can make sure that we have the max profit.
Why this is right? Image you have three stock prices a, b, c
if you buy at a and sell at c, then the profit is: c - a = c-b+b-a = (c-b)+(b-a). This means it equals you buy on day a and sell on day b, and then buy on day b and then sell on day c. This example illustrates the cumulative property of profit. Thus every transaction can be divided into multiple one-day transactions. If any one of the one-day transaction has negative profit, the final result is not max. We just remove it from the transaction. After removing all the negative-profit transactions, the result is max.
Code:
1 class Solution { 2 public: 3 int maxProfit(vector<int> &prices) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if (prices.size() == 0) return 0; 7 8 int tP, sum; 9 tP = 0; 10 for (int i=0; i<prices.size()-1; i++) { 11 sum = prices[i+1] - prices[i]; 12 if (sum > 0) 13 tP += sum; 14 } 15 16 return tP; 17 } 18 };