Best time to buy ans sell stock II:
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:
Scan the vector, add all the sub set which are non-decreasing order.
e.g.
1 2 4 2 5 7 2 4 9 0 9
(1 2 4) (2 5 7) ( 2 4 9) (0 9)
prof = 3 + 5 + 7 + 9 = 24.
(Updated 201308) Code (easier case):
class Solution { public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function int res=0; if (prices.size()<2){return res;} for (int i=1;i<prices.size();i++){ if (prices[i]>prices[i-1]){ res+=prices[i]-prices[i-1]; } } return res; } };
The source code : O(n)
class Solution {
public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function int prof=0; if (prices.size()>1){ int st=*(prices.begin()); for (int i = 1; i<prices.size();i++){ if (prices[i]>prices[i-1]) {continue;} prof+=prices[i-1]-st; st = prices[i]; } prof+=prices[prices.size()-1]-st; } return prof; } };
Can you make me understand why does this work.why is it correct.
ReplyDelete