leetcode-122-best time to buy and sell stock ii

Problem Description:

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

题目大意:

你有一个数组表示某只股票每天的市值,设计一个算法求出你过了这些天之后能够赚到的最大利润(再次买入之前必须售出)

Solutions:

利用贪心算法,只要是任何两天之内有的价值增加都能被加入总收益之中。

Code in C++:

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

        }
};