Maximize Sum from Array
Given an integer array ARR
of size N
, your objective is to perform a series of operations to maximize the sum of selected elements from the array. During each operation, you should:
- Select an element at index
i
(i.e.,ARR[i]
). - Remove one occurrence of the selected element from the array.
- Remove all occurrences of
ARR[i]-1
andARR[i]+1
from the array, if present.
Continue doing this until the array is empty. Your task is to determine the maximum possible sum of the selected elements.
Example:
Input:
ARR = [2, 3, 3, 3, 4, 5]
Output:
14
Explanation:
Select one of the '3's, removing one '3', '2', and '4'. The array becomes [3, 3, 5]. Then select the '3' two more times. The array becomes [5]. Finally, select '5'. The sum of selected elements is 3+3+3+5 = 14.
Input:
First line contains an integer 'T', the number of test cases.
For each test case:
First line contains an integer N, the size of the array.
Second line contains N space-separated integers, the elements of the array.
Output:
For each test case, output a single integer representing the maximum sum in a new line.
Constraints:
1 ≤ T ≤ 10
1 ≤ N ≤ 105
1 ≤ ARR[i] ≤ 105
- Execution time limit is 1 second.
Note:
Implementation should focus on maximizing the sum. Printing results is handled separately.
Maximize sum by selecting elements from array and removing adjacent elements.
Select element 'i' and remove 'i-1' and 'i+1' from array during each operation.
Continue until array is empty to maximize su...read more
Reviews
Interviews
Salaries
Users/Month