题解 | #买卖股票的最好时机(一)#

买卖股票的最好时机(一)

https://www.nowcoder.com/practice/64b4262d4e6d4f6181cd45446a5821ec

class Solution {
public:
    /**
     * 
     * @param prices int整型vector 
     * @return int整型
     */
    int maxProfit(vector<int>& prices) {
        // write code here
        //局部最优解
        int value = 0;
        int min = prices[0];
        int minIndex = 0;
        int max = prices[0];
        int maxIndex = 0;
        int i = 0;
        while (i<prices.size())
        {
            if (prices[i]>max)
            {
                max = prices[i];
                maxIndex = i;
            }
            if (prices[i]<min)
            {
                min = prices[i];
                minIndex = i;
                max = 0;
            }
            if (maxIndex>minIndex)
            {
                value = value>(max-min)?value:(max-min);
            }
            i++;
        }
        return value;
    }
};

全部评论
大佬牛啊,又是学习的一天
点赞 回复 分享
发布于 2023-05-28 21:30 上海
我插一句,这种方法的时间复杂度是O(n)?
点赞 回复 分享
发布于 2023-05-28 20:42 山东

相关推荐

代码飞升_不回私信人...:别这样贬低自己,降低预期,放平心态,跟昨天的自己比。做好自己,反而会效率更高心态更好,加油兄弟
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务