【LeetCode 122】关关刷题日记25-Best Time to Buy and Sell Stock II

时间:2022-05-07
本文章向大家介绍【LeetCode 122】关关刷题日记25-Best Time to Buy and Sell Stock II,主要内容包括题目、思路、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

关关的刷题日记 25 – Leetcode 122. 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).

这题目与121题的区别是,不限制买卖次数,可以进行多次交易。但是要求同一时间只能有一只股票在手里,下一次买股票之前必须把手里的股票卖掉。

思路

思路:和炒股的思想一样,最低点买入,最高点卖出,所以我们需要求单调递增区间的收益的累加和,时间复杂度O(n)。

class Solution {public:
    int maxProfit(vector<int>& prices) {
        if(prices.empty() || prices.size()==1)
            return 0;
        int re=0;
        for(int i=1; i<prices.size(); i++)
        {
            if(prices[i]>=prices[i-1])
                re+=prices[i]-prices[i-1];
        }
        return re;
    }};

人生易老,唯有陪伴最长情,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。