其他分享
首页 > 其他分享> > leetcode 买卖股票的最佳时机 II

leetcode 买卖股票的最佳时机 II

作者:互联网

 

 

比较简单常见的股票买卖问题,不限制交易的次数而去得最大利润。

 

思路一:

 

 其实很好理解,想获得最大利润,我们可以遍历数组,直接把所有股票的上升阶段都加起来即可。

 public int maxProfit(int[] prices) {
        int maxProfit=0;
        for(int i=0;i<prices.length-1;i++) 
            if(prices[i+1]>=prices[i])
                maxProfit+=prices[i+1]-prices[i];
        return maxProfit;
    }

 

思路二:

 动态规划。大概的做法就是因为不限制交易次数,所以可以用一个dp二维数组进行动态规划,第一个维度代表第几天,第二个维度代表手上是否持有股票。 具体的思路在我的算法思想:股票问题中。里面阐述了关于解决股票问题的大体思路。

    public int maxProfit(int[] prices) {
        int dp[][]=new int[prices.length+1][2];

        dp[0][1]=Integer.MIN_VALUE;
        dp[0][0]=0;
        for(int i=1;i<=prices.length;i++)
        {
            dp[i][1]=Math.max(dp[i-1][1],dp[i-1][0]-prices[i-1]);
            dp[i][0]=Math.max(dp[i-1][0],dp[i-1][1]+prices[i-1]);

        }
        return dp[prices.length][0];
    }

 

标签:int,maxProfit,public,II,最佳时机,prices,思路,leetcode,dp
来源: https://www.cnblogs.com/xxsdbk/p/15171748.html