LeetCode-Best Time to Buy and Sell Stock I&&II

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-Best Time to Buy and Sell Stock I&&II相关的知识,希望对你有一定的参考价值。

第一:题意是一个数组里保存着某支股票的股价情况。第i个为第i天的价格。求最大收益。允许买卖一次

这道题就是求最大的差值。可以记录下最小的值,然后基于最小值,找出当前的最大差值。

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length==0||prices.length==1)
        {
            return 0;
        }
        int low=prices[0],ans=0;
        for(int i=1;i<prices.length;i++)
        {
            if(low>prices[i]) low=prices[i];    //记录最小值
            else
            {
                if(prices[i]-low>ans)
                {
                    ans = prices[i]-low;
                }
            }
        }
        return ans;
    }
}

 

 

 

第二:题意在第一题的基础上允许多次买卖。但是必须先买再卖,不能连续买或者连续卖。

这道题就是求所有差值相加。可以想象将股价想象为一个折线统计图。将所有上升的段的差值相加即为结果。

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length==0||prices.length==1)
        {
            return 0;
        }
        int low = prices[0];
        int high = 0;
        int sum = 0;
        for(int i = 1;i<prices.length;i++)
        {
            if(low>prices[i])   //若当前股价低于最低值,进行低吸
            {
                low=prices[i];
            }
            else
            {
                if((i<prices.length-1)&&(prices[i+1]>prices[i]))  //若后面的值比当前值还大(还处于上升阶段)
                {
                    continue;
                }
                else     //若当前为一个顶峰点,则卖出股票
                {
                    sum = sum+prices[i]-low;    
                    low = prices[i];
                }
                
            }
        }
        return sum;
    }
}

 

以上是关于LeetCode-Best Time to Buy and Sell Stock I&&II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-Best Time to Buy and Sell Stock III[dp]

LeetCode-Best Time to Buy and Sell Stock I&&II

算法分析与设计第一周121.Best Time to Buy and Sell Stock&122. Best Time to Buy and Sell Stock II

Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock II

最强解析面试题:best-time-to-buy-and-sell-stock

最强解析面试题:best-time-to-buy-and-sell-stock