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

#include <iostream>
#include <vector>


using namespace std;

int maxProfit(vector<int> &prices) {
    size_t size = prices.size();
    
    if (size <= 1) {
        return 0;
    }

    int profit = 0;
    int buy = 0;
    int sell =  0;

    while(++sell < size) {
        //price is going down, collect profit
        if (prices[sell] < prices[sell-1]) {
            profit += prices[sell-1]-prices[buy];
            buy = sell;
        }
    }
    //collect last profit
    profit += prices[sell-1]-prices[buy];

    return profit;
}
View Program Text


Test Status