![]() |
VOOZH | about |
Given an array arr[] consisting of N elements(such that N = 2k for some k ? 0), the task is to reduce the array and find the last remaining element after merging all elements into one. The array is reduced by performing the following operation:
Examples:
Input: N = 4, arr[] = [1, 2, 3, 4]
Output: 0
Explanation: First operation:
On merging 1st and 2nd elements we will have a element with value1.
On merging 3rd and 4th elements, we will have a element with value1.
Therefore, we are left with two elements where each of them having cost 1.
Second operation:
On merging the 1st and 2nd elements we will get a new element with value 0.
This is because both elements had the same value of 1.Input: N = 1, arr[] = [20]
Output: 20
Explanation: We can't perform any operation because performing an operation requires at least 2 elements. Hence, 20 is cost of the last remaining element
Approach: This problem can be solved using the Divide and Conquer approach.
Below is the implementation of the above approach:
0
Time Complexity: O(2log2N)
Auxiliary Space: O(N)