题解 | #买卖股票的最好时机 ii#

买卖股票的最好时机 ii

https://www.nowcoder.com/practice/572903b1edbd4a33b2716f7649b4ffd4

#include <cstdio>
class Solution {
public:
    /**
     * 
     * @param prices int整型vector 
     * @return int整型
     */
    int maxProfit(vector<int>& prices) {
        // write code here
        int min = prices[0];
        int max = prices[0];
        int i = 0;
        int value = 0;
        while (i < prices.size()) 
        {
            if (prices[i]>max)
            {
                max = prices[i];
            }
            if (prices[i]<min)
            {
                min = prices[i];
            }
            if (max == prices[i]&&i+1>=prices.size())
            {
                value+=max-min;
            }
            else if (max == prices[i]&&prices[i+1]<prices[i])  
            {
                value+=max-min;
                max = prices[i+1];
                min = prices[i+1];
            }
            i++;
        }
        return value;
    }
};

全部评论
min和max初始化为prices[0这块有点没明白🤨
点赞 回复
分享
发布于 2023-05-28 20:51 山东
楼主这个代码挺容易理解的的,感谢分享
点赞 回复
分享
发布于 2023-05-28 20:51 湖北
博乐游戏
校招火热招聘中
官网直投

相关推荐

部门氛围好,不卷,欢迎投递!
投递蚂蚁集团等公司10个岗位 >
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务