按照要求保留数组元素使得和最大

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

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)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值