股票最大收益 Best Time to Buy and Sell Stock II

杜翰林
2023-12-01

题目源自于leetcode。

题目: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 num = prices.size();
        if(num <= 1)
            return 0;
            
        int sum =0;
        int min, max;
        int i=0;
        while(i < num)
        {
            while((i+1<num) && (prices[i] > prices[i+1]))
                i++;
            min = prices[i];
            
            while((i+1<num) && (prices[i] < prices[i+1]))
                i++;
            max = prices[i];
            
            sum += max - min;
            i++;
        }
        return sum;
    }
};
注意:代码写完后要认真检查,返回值不能丢,变量初始化不能丢,输入合法性检查不能忘记。

 类似资料: