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:

  1. Select an element at index i (i.e., ARR[i]).
  2. Remove one occurrence of the selected element from the array.
  3. Remove all occurrences of ARR[i]-1 and ARR[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.
AnswerBot
3d

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

Help your peers!
Add answer anonymously...
GE Digital Technology Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter