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

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

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;
    }
};

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

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务