Description
Given an array of N numbers, we need to maximize the sum of selected numbers. At each step, you need to select a number Ai, delete one occurrence of Ai-1 (if exists) and Ai each from the array. Repeat these steps until the array gets empty. The problem is to maximize the sum of selected numbers.
Input
The first line of the input contains T denoting the number of the test cases. For each test case, the first line contains an integer n denoting the size of the array. Next line contains n space separated integers denoting the elements of the array.
Constraints:1<=T<=100,1<=n<=50,1<=A[i]<=20
Note: Numbers need to be selected from maximum to minimum.
Output
For each test case, the output is an integer displaying the maximum sum of selected numbers.
Sample Input 1
2
3
1 2 3
6
1 2 2 2 3 4
Sample Output 1
4
10
def solution(l):
res = 0
while len(l) != 0:
res += l[-1]
if l[-1] - 1 in l:
l.remove(l[-1] - 1)
l.remove(l[-1])
return res
if __name__ == '__main__':
for _ in range(int(input())):
number = int(input())
l = list(map(int, input().strip().split()))
l.sort()
result = solution(l)
print(result)

本文介绍了一种在给定数组中通过特定规则选择并删除元素,以实现所选元素总和最大化的问题解决策略。该算法从数组的最大值开始,依次选择并移除当前最大值及其前一个值(如果存在),直至数组为空,最终返回所选元素的最大总和。文章通过示例输入和输出展示了算法的工作流程。
470

被折叠的 条评论
为什么被折叠?



