leetcode刷题记录 121 买卖股票的最佳时机

leetcode 121 买卖股票的最佳时机

在这里插入图片描述
思路:
1.我们买股票肯定想在最低点买入,然后在最高点卖出。那么我们设置两个变量,一个是minPrice来保存最低点的数值,maxPrice来保存最大差值。
2.我们通过遍历来寻找最低值,遇到最小值就替换minPrice。
3.比较每次求取的差值,若大过之前的最大值,就讲maxPrice替换。

class Solution {
    public int maxProfit(int[] prices) {
        int maxPrice = 0;
        int minPrice = Integer.MAX_VALUE;//找出最低点买入
        for(int i=0;i<prices.length;i++){
            if(prices[i]<minPrice){
                minPrice = prices[i];
            }else if(prices[i]-minPrice>maxPrice){
                maxPrice = prices[i] - minPrice;
            }
        }
        return maxPrice;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40453090/article/details/108411489