Quesion :


Say you have an array for which the

i


th

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).


for example: array[]  = { 2, 5, 3, 8, 9, 4 } , maxProfit = (9-8) + (8-3) + (5-2) = 1 + 5 + 2 = 8.


Anwser 1: :

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(prices.size() == 0) return 0;

        int len = prices.size();
        int ret = 0;
        for(int i = len - 1; i > 0; i--){
            if(prices[i] > prices[i-1]){
                ret += prices[i] - prices[i-1];
            }
        }
        return ret;
    }
};