码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode刷题4

时间:2019-08-08 21:37:45      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:i++   合并   stat   今天   查找   for   位置   ++   class   

今天刷的题是买卖股票的最佳时机,在求解的过程中,也参考了LeetCode的官方解答思路。

第一个解题的思路是采用递归的方法来做:当找到了一个赚钱的点后,更新搜索范围,继续查找。最后把所有的赚钱的加起来就对了。

第二个是采用峰谷法。首先是峰谷都是起点。先查找谷的位置。谷的位置就是前面的点都比后面的点大。然后在谷的位置之后查找峰的位置。锋的位置就是后面的点比前面的点大。然后再累加即可。

第三个方法是动态规划。状态转移方程是:prices[i]=prices[i-1](if prices[i]<=prices[i-1]) or prices[i]=prices[i-1]+prices[i-1]-prices[i] (if prices[i]>prices[i-1])

三种方法的代码如下:

public class MaxProfit {
    /**
     * @Description 当输入[7,1,5,3,6,4]的时候,输出为 7
     * 这是因为在第二天以价格为1买入,第三天以价格为5卖出,赚4
     * 第四天以价格为3买入,第五天以价格为6卖出,赚3
     * 合并起来赚7
     */
    public static int max(int[] prices){
        return caculate(prices,0);
    }
    public static int caculate(int[] prices,int s){
        if (s>=prices.length){
            return 0;
        }
        int max=0;
        for (int start=s;start<prices.length;start++){
            int maxProfit=0;
            for (int i = start+1; i <prices.length ; i++) {
                if (prices[start]<prices[i]){
                    int profit=caculate(prices,i+1)+prices[i]-prices[start];
                    if (profit>maxProfit){
                        maxProfit=profit;
                    }
                }
            }
            if (maxProfit>max)max=maxProfit;
        }
        return max;
    }
    public static int max1(int[] prices){
        if (prices.length==0)return 0;
        int i=0;
        int maxprofit=0;
        int peak=prices[0];
        int valley=prices[0];
        while (i<prices.length-1){
            while (i<prices.length-1 && prices[i]>=prices[i+1]){
                i++;
            }
            valley=prices[i];
            while (i<prices.length-1 && prices[i]<=prices[i+1]){
                i++;
            }
            peak=prices[i];
            maxprofit+=peak-valley;
        }
        return maxprofit;
    }
    public static int max2(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;
    }
}

 

leetcode刷题4

标签:i++   合并   stat   今天   查找   for   位置   ++   class   

原文地址:https://www.cnblogs.com/cquer-xjtuer-lys/p/11323576.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!