原题链接:
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/
解法1:
贪心
只要是股票上涨日 就进行买卖那就必赚
只用算隔天涨幅赚的钱即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
   | class Solution {     public int maxProfit(int[] prices) {         int n = prices.length;         int ans = 0;         for(int i = 0 ; i < n - 1 ; i++){             int tmp = prices[i + 1] - prices[i];             if(tmp > 0){                 ans += tmp;             }         }
          return ans;     } }
 
  | 
 
解法2:
动态规划
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
   | 
 
 
 
 
 
 
 
 
  class Solution {     public int maxProfit(int[] prices) {         int n = prices.length;         int [][] f = new int[n + 1][2];                  f[0][0] = 0;                  f[0][1] = -prices[0];                  for(int i = 1 ; i < n ; i++){                          f[i][0] = Math.max(f[i - 1][1] + prices[i],f[i - 1][0]);                          f[i][1] = Math.max(f[i - 1][0] - prices[i],f[i - 1][1]);         }                  return  Math.max(f[n - 1][0],f[n - 1][1]);     } }
 
  | 
 
更进一步的可以在空间上进行优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
   | 
 
 
  class Solution {     public int maxProfit(int[] prices) {         int n = prices.length;                  int [] cash = new int[n];                  int [] hold = new int[n];                                    cash[0] = 0;                  hold[0] = -prices[0];           for(int i = 1 ; i < n ; i++){                                       cash[i] = Math.max(cash[i - 1],hold[i - 1] + prices[i]);  
                                        hold[i] = Math.max(hold[i - 1],cash[i - 1] - prices[i]);         }                  return cash[n - 1];     } }
 
 
  | 
 
在上一步基础可以观察到 cash 和 hold都只涉及到上一步的变量因此 我们可以用滚动数组进一步优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
   | 
 
 
  class Solution {     public int maxProfit(int[] prices) {         int n = prices.length;                  int cash = 0 ;                  int hold = 0;                                    cash = 0;                  hold = -prices[0];
          int preCash = cash;         int preHold = hold;
          for(int i = 1 ; i < n ; i++){                                       cash = Math.max(preCash,preHold + prices[i]);  
                                        hold = Math.max(preHold,preCash - prices[i]);
                           preCash = cash;             preHold = hold;         }                  return cash;     } }
 
 
  |