System Charge Combination

Moderate
0/80
0 upvote
Asked in company
Amazon

Problem statement

You are given an array charge of size n, where charge[i] represents the charge value of a system.


You must remove all systems one by one until only a single system remains. The goal is to perform these removals in an order that maximizes the charge of this final remaining system.


The operation is defined as follows:


1) When you select and remove a system, its immediate left and right neighbors (if they exist) merge.


2) The new merged system has a charge equal to the sum of the charges of the two neighbors that were merged.


3) Systems at the ends of the current array (the first or last) cannot cause a merge when removed, as they only have one neighbor.


Your task is to find the maximum possible charge of the final system.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains an integer 'N', the size of the array.

The second line contains 'N' space-separated integers, representing the elements of the charge array.


Output Format:
Print a single integer representing the maximum possible charge of the final system.


Note:
A simple greedy approach does not work. The optimal strategy often involves removing elements that result in a smaller immediate merge cost to set up a larger merge later.
Sample Input 1:
4
3 2 4 5


Sample Output 1:
51


Explanation for Sample 1:
We can form the following three pairs:
1. (10, 5) since 10 > 5
2. (20, 15) since 20 > 15
3. (30, 25) since 30 > 25
All elements are used, and we have a total of 3 pairs, which is the maximum possible.


Sample Input 2:
4
1 2 8 9
3 4 5 6


Sample Output 2:
2


Explanation for Sample 2:
The optimal way to form pairs is:
1. (8, 3) since 8 > 3
2. (9, 4) since 9 > 4
The elements 1 and 2 from array 'a' cannot be paired with any remaining elements from array 'b' (5 and 6). The maximum number of pairs is 2.


Expected Time Complexity:
The expected time complexity is O(n log n).


Constraints:
1 <= n <= 10^5
-10^9 <= a[i], b[i] <= 10^9

Time limit: 1 sec
Approaches (1)
Dynamic Programming
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
System Charge Combination
Full screen
Console