【leetcode】Best Time to Buy and Sell 2(too easy)

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

题目意思:就是可以多次买卖股票,问最多赚多少钱。

思路:对于数组,从头到尾遍历,遇到递增的就把递增差值加入的收入就行了.(只要涨就买,跌就卖)

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.empty())
        {
            return 0;
        }
        int maxprofit = 0;
        int last = prices[0];
        vector<int>::iterator it;
        for(it = prices.begin() + 1; it < prices.end(); it++)
        {
            if(*it > last)
            {
                maxprofit += (*it - last);
            }
            last = *it;
        }
        return maxprofit;
    }
};
原文地址:https://www.cnblogs.com/dplearning/p/4110945.html