Codeforces Round 1133 (Div. 1, Div. 2) is coming soon! Register here. ×

kstheking's blog

By kstheking, history, 6 years ago, In English

Problem: Given N elements, in one operation you can merge adjacent elements (i.e. sum them up into one element), you have to do exactly K operations, what is the minimum possible obtainable value of the maximum of the resultant array.

Example
Elements: 1 2 3
K : 1
Output: 3 (by merging 1 and 2 we get 3, if we merged 2 and 3 we would get 5 which is > 3)

I can do this problem in O(N^2) complexity by Dynamic Programming, but can better time complexity be achieved?

  • Vote: I like it
  • -13
  • Vote: I do not like it

| Write comment?
»
6 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Problem Source? constraints?

»
6 years ago, hide # |
 
Vote: I like it +5 Vote: I do not like it

How are you solving in N^2?

»
6 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Create a min heap of all the elements in an array. Remove the top 2 elements, add them and insert in the heap. Do this k times.

Time Complexity: O(klogn)

»
6 years ago, hide # |
 
Vote: I like it +4 Vote: I do not like it

I think you can solve this problem using binary search . Let's fix $$$mx$$$ , means the max element after performing $$$k$$$ operations would not be greater than $$$mx$$$ .
Now create a stack and start pushing elements in the stack . Now if the stack has at least 2 elements then take top 2 elements from the stack and check if there sum is less or equal to $$$mx$$$ . Now if the sum is less or equal to $$$mx$$$ , it means you can perform an operation here otherwise you can't .
Now in the end if you were able to perform $$$k$$$ operations then return $$$true$$$ otherwise return $$$false$$$ and set $$$low$$$ and $$$high$$$ of binary search accordingly .