best-time-to-buy-and-sell-stock-ii leetcode C++

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

C++

class Solution {
public:
    int maxProfit(vector<int>& prices){
        int res = 0;
        int n = prices.size() - 1;
        for (int i = 0; i < n; ++i){
            if (prices[i] < prices[i+1])
                res += prices[i + 1] - prices[i];
        }
        return res;
    }
};

 

posted @ 2018-09-20 00:40  vercont  阅读(88)  评论(0编辑  收藏  举报