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

思路:

可以将n个价格的数组转化成n-1个隔日的盈亏数组,即表示前一日买后一日卖的收入。目标问题变成了将第二个数组中数值大于0的数的最大值。

题目:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
         if(prices.size() == 0 || prices.size() == 1)
        {
            return 0;
        }
        
        int* profit = new int[prices.size()-1];
        
        for(int i = 0; i < prices.size()-1; i++)
        {
            profit[i] = prices[i+1]-prices[i];
        }
        
        int max = 0;
        for(int i = 0; i < prices.size()-1; i++)
        {
            if(profit[i] > 0)
            {
                max += profit[i];
            }
        }
        
        return max;
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11880385
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞