【LeetCode122】-买卖股票的最佳时机 II

方法一

这题是在 【LeetCode121】买卖股票的时机基础上的一道题目

实现思路

实现思路只要两天股票差值大于0即可买入和卖出得到利润,所以将所有两天利润大于0的值累加即可得到最大利润

实现代码

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

提交结果及分析

在这里插入图片描述
空间复杂度O(n)
时间复杂度O(n)

猜你喜欢

转载自blog.csdn.net/weixin_44944046/article/details/113799806