Advertisement
Guest User

LC_123

a guest
Jun 16th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.65 KB | None | 0 0
  1. class Solution {
  2.     // public int maxProfit(int[] prices) {
  3.     //     if (prices.length==0) return 0;
  4.     //     int K = 2;
  5.     //     int[][] dp = new int[K+1][prices.length];
  6.     //     for (int k=1 ; k<= K; k++) {
  7.     //         for (int i=1; i<prices.length; i++) {
  8.     //             int min = prices[0];    
  9.     //             for (int j=1;j<=i;j++) {
  10.     //                 min = Math.min(min,prices[j]-dp[k-1][j-1]);
  11.     //             }
  12.     //             dp[k][i]=Math.max(dp[k][i-1], prices[i]-min);
  13.     //         }
  14.     //     }
  15.     //     return dp[K][prices.length-1];
  16.     // }
  17.     public int maxProfit(int[] prices) {
  18.         if (prices.length<=1) return 0;
  19.         int[] dp = new int[prices.length];
  20.        
  21.         int min = prices[0];
  22.         int max = 0;
  23.         for (int i=1; i<prices.length;i++) {
  24.             if ((prices[i]-min) > max) max = prices[i]-min;
  25.             dp[i]=max;
  26.             // System.out.println("max: "+max);
  27.             if (min > prices[i]) min = prices[i];
  28.         }
  29.         // System.out.println("max: "+dp[dp.length-1]);
  30.         // 2nd iteration
  31.         max = prices[prices.length-1];
  32.         int secProfit = 0;
  33.         int totalMax = dp[prices.length-1], localMax;
  34.         for (int i=prices.length-2; i>0; i--) {
  35.             // System.out.println("processing index: "+i);
  36.             if ((max-prices[i]) > secProfit) secProfit = max-prices[i];
  37.             // System.out.println("sec profit: "+secProfit);
  38.             localMax = dp[i-1]+secProfit;
  39.             if (localMax > totalMax) totalMax = localMax;
  40.             if (prices[i]>max) max = prices[i];
  41.         }
  42.         return totalMax;
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement