-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBest_time_to_buy_and_sell_stock_II
36 lines (32 loc) · 1.11 KB
/
Best_time_to_buy_and_sell_stock_II
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
Best Time to Buy and 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).
*/
class Solution {
public:
int maxProfit(vector<int> &prices) {
if (prices.size()==0) return 0;
int buyprice=prices[0], sellprice=prices[0];
int profit=0;
for (int i=1; i<prices.size();++i)
{
if (prices[i-1]>prices[i])
{
sellprice=prices[i-1];
profit += (sellprice-buyprice);
buyprice=prices[i];
}
}
profit += (prices[prices.size()-1]-buyprice);
return profit;
}
};
1.Hard one. Why didn't i figure it out?
IDEA:
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.
2. Time complexity: O(n).