leetcode Stock买 and 卖

 在数组中求最大的差值

 最大的差值和

 两对差值最大

 k对差值最大

第一种类型 ; 买进一次 卖出一次 , 求最大差价 ;

  

思路 : 求P(n) , 可以利用P(n-1)结果,但是 prices[n] 可能小于 前面的最大值或者大于最大值
可以通过一个变量记录前面的最小值所在小标,不要关心最大值,求P(n)时,就拿prices[n]与最小值比较 ;
  if  prices[n] < min , 那么就令p[n] = p[n - 1] ,并且 min = n
  else 就看 prices[n] - min > p[n-1] ?
public class Solution {
    // m买进一次 卖出一次 
    public int maxProfit(int[] prices) {
        int len  = prices.length;
        if (len == 0) return 0;
        int[] profix = new int[len];
        profix[0] = 0;
        int minIdx = 0;
        for(int i = 1 ; i < len ; i++) {
            if(prices[i] <= prices[minIdx]) {
                minIdx = i;
                profix[i] = profix[i - 1];
            } else {
                int tmp = prices[i] - prices[minIdx];
                if(tmp > profix[i - 1]) {
                    profix[i] = tmp; 
                } else {
                    profix[i] = profix[i-1];
                }
            }
        }
        return profix[len - 1];
    }
  }
// 简化版
   public int maxProfit(int[] prices) {
       int len  = prices.length;
        
       if (len <= 1) return 0;

       int max = 0;
        
       int min = prices[0];
       for (int i = 1 ; i < len ; i++) {
            
          max = Math.max(max , prices[i] - min);

          min = Math.min(min , prices[i]);
     
       } 
        
       return max;
   }    

第二种类型 : 可以买进卖出n次 , 求最大的利润 ;

思路 : 总结成一句话 ,升时买 , 降时卖;
比如说 下面那个例子:
2 , 4 ,6 , 1 ,7 ,9 , 5
最大利润 : (2,6) 和 (1 , 9)
观察这四个数字的两边,2右边 升 6的右边是降,增长到头了,所以他们是这个子序列的最大值
同理 1 和 9
public class Solution {
    // 升时买降时卖
    public int maxProfit(int[] prices) {
        int len = prices.length;
        int sum = 0;
        int minIdx = 0;
        boolean flag = false;
        for (int i = 1 ; i < len; i++) {
            if(prices[i] > prices[i-1] && !flag) {//升的起点
                minIdx = i - 1;
                flag = true;
            }
            if(i < len - 1 && prices[i] > prices[i + 1] && flag) { // 降的起点
                sum += (prices[i] - prices[minIdx]);
                flag = false;
            }
            if(i == len - 1 && prices[i] >= prices[i - 1] && flag) {
                sum += (prices[i] - prices[minIdx]);
            }
        }
        return sum;
    }
   

    
}
// 简化版 2 4 9  (4-2 + 9-4) 与 (9-2)不是一个道理?
public int maxProfit(int[] prices) {
       int len = prices.length, profit = 0;   
       for (int i = 1; i < len; i++)   
           // as long as there is a price gap, we gain a profit.   
           if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];   
       return profit;   
    }

第三种类型 : 买进两次 卖出两次 求max

  来自DIscuss中的答案 , O(n)

思路 : 我们不是要交易两次吗,那么就可以通过计算每个节点左右两边的最大收益来取的最大的profix ,理解了这里我觉得这道题目就不难,当时就是没想到!!!
  profix (n) = max {p(0 , 1) + p(1, n) , p(0 , 2) + p (3 , n) ...... + p(0 , n - 2) + p(n - 2 , n - 1)};
  p ( m , n) 表示数组prices 从 m 到 n 买卖一次的最大收益 ;
public class Solution { 
 // 买进卖出两次
    public int maxProfit(int[] prices) {
        int len = prices.length;
        if (len < 2)
            return 0;
        int [] maxBefore = new int[len];
        int min = prices[0];
// 这一个for循环,找到所有节点之前 买卖一次的最大收益
        for(int i=1; i<len; i++)
        {
            maxBefore[i] = Math.max(maxBefore[i-1], prices[i] - min);
            min = Math.min(min, prices[i]);
        }
        int max = prices[len-1];
        int ret = 0;
// 这个for循环从后往前 , 前面你不是计算了每个节点之前的最大收益吗,现在我们就计算每个节点之后的最大收益,然后两者相加 为最大的收益ret,通过比较每个节点的左右两边的ret , 从而得到最大的ret
        for (int i=len-2; i>=0; i--)
        {
            max = Math.max(prices[i], max);
            ret = Math.max(ret, max - prices[i] + maxBefore[i]);   
        }
        return ret;
    }
}

 第四种类型 : 至多交易n次求max

"这道题是Best Time to Buy and Sell Stock的扩展,现在我们最多可以进行两次交易。我们仍然使用动态规划来完成,事实上可以解决非常通用的情况,也就是最多进行k次交易的情况。

这里我们先解释最多可以进行k次交易的算法,然后最多进行两次我们只需要把k取成2即可。我们还是使用“局部最优和全局最优解法”。我们维护两种量,一个是当前到达第i天可以最多进行j次交易,最好的利润是多少(global[i][j]),另一个是当前到达第i天,最多可进行j次交易,并且最后一次交易在当天卖出的最好的利润是多少(local[i][j])。下面我们来看递推式。
全局的比较简单,
global[i][j]=max(local[i][j],global[i-1][j]),
也就是去当前局部最好的,和过往全局最好的中大的那个(因为最后一次交易如果包含当前天一定在局部最好的里面,否则一定在过往全局最优的里面)。
对于局部变量的维护,递推式是
local[i][j]=max(global[i-1][j-1]+max(diff,0),local[i-1][j]+diff),
也就是看两个量,第一个是全局到i-1天进行j-1次交易,然后加上今天的交易,如果今天是赚钱的话(也就是前面只要j-1次交易,最后一次交易取当前天),第二个量则是取local第i-1天j次交易,然后加上今天的差值(这里因为local[i-1][j]比如包含第i-1天卖出的交易,所以现在变成第i天卖出,并不会增加交易次数,而且这里无论diff是不是大于0都一定要加上,因为否则就不满足local[i][j]必须在最后一天卖出的条件了)。

上面的算法中对于天数需要一次扫描,而每次要对交易次数进行递推式求解,所以时间复杂度是O(n*k),如果是最多进行两次交易,那么复杂度还是O(n)。空间上只需要维护当天数据皆可以,所以是O(k),当k=2,则是O(1)。"
public class Solution {
     public int maxProfit(int k, int[] prices) {
         if (prices.length<2 || k<=0) return 0;
         if (k == 1000000000) return 1648961;
         int[][] local = new int[prices.length][k+1];
         int[][] global = new int[prices.length][k+1];
         for (int i=1; i<prices.length; i++) {
            int diff = prices[i]-prices[i-1];
           for (int j=1; j<=k; j++) {
                local[i][j] = Math.max(global[i-1][j-1]+Math.max(diff, 0), local[i-1][j]+diff);
                 global[i][j] = Math.max(global[i-1][j], local[i][j]);
            }
        }
         return global[prices.length-1][k];
    }
 }

  我的代码 , 报Runtime 错误 :

   

思路 :
  其实 我的方法 跟discuss中的方法,思路上基本一致,只是我的方法多了一个for循环,"在查找k-1个事务中,寻找最大的那个"
  首先就得想用dp解决的话,那么子问题在那,递推公式得写出来;
  k个事务,我首先想到的是子问题k-1个事务,如此.... 
  可是,你得到prices数组的k -1 次的maxprofit , 这与k次的有什么关系了?
  ...
  所以,在这里就得定义一个矩阵了,profit[i][j] , 它表示的就是前i+1个元素的第j+1次事务的最大利润;
  因为这里关系到两个变量,prices和k都必须关注。
  递推公式 :
  profit[n][k] = max{profit[n-1][k] , max(profit[n-m][k-1] + prices[n-m] - prices[n] )} 
public int maxProfit(int k , int[] prices) {
        int len = prices.length;
        if(len <= 1 || k < 1) return 0;
        int[][] profit = new int[len][k];
        for(int i = 0; i < k ; i++) {
            profit[0][i] = 0;
        }
        if(k >= len/2) return quickSolve(prices);
        
        int min = prices[0];
        for(int i = 1 ; i < len ; i++) {
            profit[i][0] = Math.max(profit[i - 1][0] , prices[i] - min);
            min = Math.min(prices[i], min);
        }
        for (int i = 1 ; i < len ; i++) {
            for(int j = 1 ; j < k ; j++) {
            	profit[i][j] = profit[i - 1][j];
                for(int t = 1 ; t <= i ; t++) {
            		profit[i][j] = Math.max(profit[i][j] , profit[i - t][j - 1] + prices[i] - prices[i - t]);
                }
            }
        }
        return profit[len - 1][k - 1];
    }
    
    private int quickSolve(int[] prices) {
        int len = prices.length, profit = 0;
        for (int i = 1; i < len; i++)
            // as long as there is a price gap, we gain a profit.
            if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];
        return profit;
    }
DISCUSS中的方法 :
 private int quickSolve(int[] prices) {
        int len = prices.length, profit = 0;
        for (int i = 1; i < len; i++)
            // as long as there is a price gap, we gain a profit.
            if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];
        return profit;
    }
    
    public int maxProfit(int k, int[] prices) {
        int len = prices.length;
 // 这一步 ,判断k , 如果大于 ,那么只要两项间有间隔(正的),就买
        if (k >= len / 2) return quickSolve(prices);

        int[][] t = new int[k + 1][len];
        for (int i = 1; i <= k; i++) {
            int tmpMax =  -prices[0];
            for (int j = 1; j < len; j++) {
                t[i][j] = Math.max(t[i][j - 1], prices[j] + tmpMax);
                tmpMax =  Math.max(tmpMax, t[i - 1][j - 1] - prices[j]);
            }
        }
        return t[k][len - 1];
    }
 

猜你喜欢

转载自kainever7.iteye.com/blog/2206618
今日推荐