Advertisement
ogv

Untitled

ogv
Nov 5th, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.93 KB | None | 0 0
  1. // Runtime: 4 ms, faster than 89.16% of Java online submissions for Partition Array for Maximum Sum.
  2. class Solution {
  3.     public int maxSumAfterPartitioning(int[] A, int K) {
  4.         return part(A, K, 0, new int[A.length]);
  5.     }
  6.    
  7.     public int part(int[] A, int K, int from, int[] dp) {
  8.         if (from >= A.length) return 0;
  9.         if (dp[from] != 0) return dp[from];
  10.        
  11.         int result = 0;
  12.        
  13.         int maxCount = Math.min(K, A.length - from);
  14.        
  15.         int[] max = new int[maxCount];
  16.         max[0] = A[from];        
  17.         for (int i = 1; i < maxCount; i++)
  18.             max[i] = Math.max(max[i-1], A[from + i]);
  19.        
  20.         for (int count = 1; count <= maxCount; count++) {            
  21.             int r  = max[count - 1] * count + part(A, K, from + count, dp);
  22.             if (r > result) result = r;
  23.         }
  24.        
  25.         dp[from] = result;        
  26.         return result;
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement