You are given an array of n integers and an integer k. Your task is to divide the array into exactly k non-empty, contiguous subarrays (or "parts").
For each subarray, you must calculate its "value". The value of a subarray is defined as:
(sum of its elements) - (its minimum element) + (its maximum element)
The goal is to find a partitioning of the original array into k parts such that the sum of the values of all k parts is maximized.
Return this maximum possible total value.
The first line contains two space-separated integers, n and k.
The second line contains n space-separated integers, representing the elements of the array.
Your function should return a single integer representing the maximum possible total value. The runner code will handle printing.
The problem has optimal substructure and overlapping subproblems, making it a classic fit for dynamic programming. A state dp[i][j] could represent the maximum value achievable by splitting the first j elements of the array into i parts. To calculate dp[i][j], you would iterate through all possible split points p < j and consider the value of the last part [p...j-1].
dp[i][j] = max(dp[i-1][p] + valueofsubarray(p to j-1))
4 2
1 5 2 6
22
The array is [1, 5, 2, 6] and must be split into k=2 parts.
Split Option 1: [1] and [5, 2, 6]
Value of [1]: sum=1, min=1, max=1 -> 1 - 1 + 1 = 1
Value of [5, 2, 6]: sum=13, min=2, max=6 -> 13 - 2 + 6 = 17
Total Value: 1 + 17 = 18
Split Option 2: [1, 5] and [2, 6]
Value of [1, 5]: sum=6, min=1, max=5 -> 6 - 1 + 5 = 10
Value of [2, 6]: sum=8, min=2, max=6 -> 8 - 2 + 6 = 12
Total Value: 10 + 12 = 22
Split Option 3: [1, 5, 2] and [6]
Value of [1, 5, 2]: sum=8, min=1, max=5 -> 8 - 1 + 5 = 12
Value of [6]: sum=6, min=6, max=6 -> 6 - 6 + 6 = 6
Total Value: 12 + 6 = 18
The expected time complexity is O(N^2 * K).
1 <= k <= n <= 1000
1 <= array element <= 10^6