LeetCode--121. Best Time to Buy and Sell Stock && 122. Best Time to Buy and Sell Stock II

连续AC了5条medium有点疲惫,休息一下来两条easy放松放松。

题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

题目一要求找到股票最佳的买入卖出时间(最大化利润)

思路一:暴力计算每种可能性

class Solution {
    
    public int maxProfit(int[] prices) {
        int max=0;
        for(int i=0;i<prices.length-1;i++)
            for(int j=i+1;j<prices.length;j++)
                max=Math.max(max,prices[j]-prices[i]);
        return max;
    }
}

思路二:维护一个最小股价和最大利润的变量

class Solution {
    
    public int maxProfit(int[] prices) {
        int minPrice=Integer.MAX_VALUE;
        int maxProfit=0;
        
        for(int i=0;i<prices.length;i++)
        {
            minPrice=Math.min(minPrice,prices[i]);
            
            maxProfit=Math.max(maxProfit,prices[i]-minPrice);
        }
        return maxProfit;
    }
}

题目二要求多次买入卖出的最大收益,实际上是在求所有股票增长阶段收益的综合,使用双指针来解决就可,代码也比较简单,注意边界条件的判断即可:

class Solution {
    public int maxProfit(int[] prices) {
        
        int maxProfit=0;
        int i=0,j=0;
        while(j<prices.length-1)
        {
            while(j<prices.length-1 && prices[j+1]>prices[j])
                j++;
            if(j!=i)
                maxProfit += prices[j]-prices[i];
            i=j+1;
            j=i;         
        }
        return maxProfit;
    }
}

猜你喜欢

转载自blog.csdn.net/To_be_to_thought/article/details/85541741