122. 买卖股票的最佳时机 II

https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/solution/

暴力

  本题可以多次买卖股票,如果只允许一次买卖股票,整个暴力就是n2的算法,如果可以无限制买卖股票直接用普通的写法不是很好写,可以用递归来解决。先考虑只允许一次买卖的暴力解法,双层循环,外层循环i代表买入股票的时机,内层j循环从i+1开始,代表买入股票后的股票价格,如果发现prices[j]>prices[i]就尝试卖掉并和全局max比较,如果大于全局max就更改。但本题可以无限买卖股票,所以在一次买卖后还可以接着买卖,这样问题就变化为了在i买入j卖出后,在j到prices.length的范围内继续买卖,原问题转化为了子问题,这很递归。

  每次i买入股票j卖出股票后,对j+1以后的股票递归调用,int s代表股票开始的位置。

  这里用了两个临时变量来存储可能的最大值。max代表全局最大值,放在最外层的循环,代表从索引s开始买卖股票能够获取的最大的利润。maxProfit放在内层循环,当i等于s时,代表从s买股票能够获得的最大利润,每次算出maxProfit用于和max比较并更新max。

public class maxProfit_122 {
    public int maxProfit(int[] prices) {
        return cal(prices,0);
    }

    public int cal(int[] prices,int s){
        if (s>=prices.length){
            return 0;
        }

        int max = 0;
        for (int i=s;i<prices.length;i++){
            int maxProfit = 0;
            for (int j=i+1;j<prices.length;j++){
                if (prices[j]>prices[i]){
                    int tempProfit = cal(prices, j + 1) + prices[j] - prices[i];
                    maxProfit = tempProfit>maxProfit?tempProfit:maxProfit;
                }
            }
            max = maxProfit>max?maxProfit:max;

        }
        return max;
    }

波峰波谷

  因为买卖次数是无限的,所以把问题转化为求整个股票价格序列中所有波峰和波谷之差之和。遍历整个数组,找到波谷,找到波峰,相减。

  先不考虑开始,假设现在处在循环之中。比较i和i+1,如果i大于i+1说明这是递减区间,一直往下走,直到i不再大于i+1说明递减区间结束,i不再大于i+1说明i<i+1,此时i的值为波谷,这个很简单,导数异号说明来到了极值。用同样的方法找到最大值,然后相减即为一次买卖的利润。

  其次关注初始条件的设置,low high都设置为Index等于0的数。如果数组的第一个区间是递增的,那么low就是0。

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length == 0){
            return 0;
        }
        int i = 0;
        int low = prices[0];
        int high = prices[0];
        int result=0;

        while (i<prices.length-1){
            while (i<prices.length-1 && prices[i]>=prices[i+1]){
                i++;
            }
            low = prices[i];
            while (i<prices.length-1 && prices[i]<=prices[i+1]){
                i++;
            }
            high = prices[i];
            result+=high-low;
        }
        return result;
    }
}
原文地址:https://www.cnblogs.com/AshOfTime/p/10812853.html