[LeetCode] Best Time to Buy and Sell Stock II

Best Time to Buy and Sell Stock II

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) {
        int len = prices.size();
        if(len==0 || len==1){
            return 0;
        }
        int result = 0;
        for(int i=1; i<len; i++){
            if(prices[i]>prices[i-1]){
                result += prices[i] - prices[i-1];
            }
        }
        return result;
    }
};


0 条评论

    发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注