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
4mo

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!
Select
Add answer anonymously...
GE Digital Technology Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

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

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits