【leetcode】Best Time to Buy and Sell Stock II

Quesion :

Say you have an array for which theithelement is the price of a given stock on dayi.

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;
    }
};


你可能感兴趣的:(LeetCode)