Dividing an array into K subarrays to reduce the largest possible difference.

Revision en1, by BedwarKing, 2024-09-22 12:20:47

First of all, Sorry for my poor English.

I know there's a blog which discusses about this problem before: https://mirror.codeforces.com/blog/entry/52860. However I am not really understand the solution for it.

Well, here's the problem statement: You are given an array $$$a$$$ with $$$n$$$ elements. Your task is to divide the array $$$a$$$ into $$$k$$$ subarrays so that the difference between the largest and the smallest value of all subarrays is minimum (The value of a subarray is the sum of all elements in that subarray). Constraints: $$$ 1 \leq K \leq N \leq 250,\ 0 \leq a[i] \leq 10^6\ \forall i \in [1, n] $$$

So let's take an example: $$$N=6$$$ and $$$K=3$$$ and the array $$$a = {7, 4, 6, 1, 2, 10}$$$

The optimal way is to split it into $$$[7, 4][6, 1, 2][10] \rightarrow$$$ The value of each subarray is $$$11\ (= 7 + 4), 9\ (= 6 + 1 + 2), 10\ (= 10)$$$. Here the largest value is $$$11$$$ and the smallest one is $$$9$$$ so the answer is $$$11 - 9 = 2$$$

Actually I did attempt to code this problem. If you want to see, I put it below

Code

My algorithm is to use Dynamic Programming where $$$dp[i][j]$$$ denotes the answer for the segment from $$$1$$$ to $$$i$$$ which is being divided into $$$j$$$ subarrays. So the final answer would be $$$dp[N][K]$$$ and time complexity would be $$$O(N^2 \times K)$$$. However, I don't know if this is the exact solution which solves all the cases for this problem. Therefore, I want you guys to point me out is there any errors in my code as well as give me some hints if they are wrong. Thanks a lot!

Tags dp, subarray

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English BedwarKing 2024-09-22 12:20:47 3059 Initial revision (published)