import
java.util.Arrays;
public
class
PartitionArrayMaxMinDifference {
public
static
int
maxSumAfterPartitioning(
int
[] arr,
int
k) {
int
n = arr.length;
int
[] dp =
new
int
[n +
1
];
for
(
int
s = n -
1
; s >=
0
; s--) {
int
currSum = Integer.MIN_VALUE;
int
maxElement = Integer.MIN_VALUE;
for
(
int
i = s; i < Math.min(s + k, n); i++) {
maxElement = Math.max(maxElement, arr[i]);
currSum = Math.max(currSum, dp[i +
1
] + maxElement * (i - s +
1
));
}
dp[s] = currSum;
}
return
dp[
0
];
}
public
static
int
minSumAfterPartitioning(
int
[] arr,
int
k) {
int
n = arr.length;
int
[] dp =
new
int
[n +
1
];
for
(
int
s = n -
1
; s >=
0
; s--) {
int
currSum = Integer.MAX_VALUE;
int
minElement = Integer.MAX_VALUE;
for
(
int
i = s; i < Math.min(s + k, n); i++) {
minElement = Math.min(minElement, arr[i]);
currSum = Math.min(currSum, dp[i +
1
] + minElement * (i - s +
1
));
}
dp[s] = currSum;
}
return
dp[
0
];
}
public
static
void
main(String[] args) {
int
[] arr = {
3
,
7
,
2
,
2
,
6
};
int
k =
2
;
int
maxSum = maxSumAfterPartitioning(arr, k);
int
minSum = minSumAfterPartitioning(arr, k);
int
difference = maxSum - minSum;
System.out.println(difference);
}
}