zoukankan      html  css  js  c++  java
  • leetcode刷题4

    今天刷的题是买卖股票的最佳时机,在求解的过程中,也参考了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;
        }
    }
  • 相关阅读:
    C#显示接口实现和隐式接口实现
    JAVA8新特性总结一(接口函数默认实现)
    接口(策略设计模式)
    自定义注解
    C# Task的GetAwaiter和ConfigureAwait
    UNIX(编程-进程处理):30---僵死进程、孤儿进程(SIGCLD、SIGHCLD信号处理)
    C# 静态变量会被gc回收么?
    C# 托管资源与非托管资源
    WebSocket与消息推送
    Quartz.NET实现作业调度
  • 原文地址:https://www.cnblogs.com/cquer-xjtuer-lys/p/11323576.html
Copyright © 2011-2022 走看看