Skip to content

Commit cac7efe

Browse files
authored
Update Q-07: Partition Array for Maximum Sum.java
1 parent 0780ba6 commit cac7efe

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

DP MCM Pattern/Q-07: Partition Array for Maximum Sum.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,4 +91,29 @@ public static int solveMemo(int arr[],int k,int i,int j){
9191
memo[i][j]=ans;
9292
return ans;
9393
}
94+
public int solveTab(int[] arr,int k){
95+
int n = arr.length;
96+
int[][] dp = new int[n+1][n+1];
97+
98+
for(int i=n-1;i>=0;i--){
99+
for(int j=0;j<n;j++){
100+
if(i==j) dp[i][j]=arr[i];
101+
else if(j-i+1<=k){
102+
int max=0;
103+
for(int x=i;x<=j;x++){
104+
max= Math.max(max,arr[x]);
105+
}
106+
dp[i][j] = max*(j-i+1);
107+
}else{
108+
int maxi = 0;
109+
for(int p=i;p<j && p<i+k;p++){
110+
int res = dp[i][p]+dp[p+1][j];
111+
maxi = Math.max(maxi,res);
112+
}
113+
dp[i][j]=maxi;
114+
}
115+
}
116+
}
117+
return dp[0][n-1];
118+
}
94119
}

0 commit comments

Comments
 (0)