Leetcode-1005 Maximize Sum Of Array After K Negations(K 次取反后最大化的数组和)

C++解LeetCode题:K次取反后的最大数组和
本文分享了一个C++解决方案,用于解决LeetCode上的一道题目,即如何通过最多K次取反某些元素来最大化数组的总和。通过巧妙的分类讨论和数组操作,该算法能有效地找到最优解。
 1 #define pb push_back
 2 #define _for(i,a,b) for(int i = (a);i < (b);i ++)
 3 const int maxn = 50003;
 4 
 5 class Solution
 6 {
 7     public:
 8         int largestSumAfterKNegations(vector<int>& A, int K)
 9         {
10             int hash[202] {0};
11             int fnum = 0;
12             _for(i,0,A.size())
13             {
14                 if(A[i]<0)
15                     fnum ++;
16                 hash[A[i]+100] ++;
17             } 
18             if(fnum<=K)
19             {
20                 
21                 _for(i,0,100)
22                 {
23                     hash[200-i] += hash[i];
24                     hash[i] = 0; 
25                 }
26                 K -= fnum;
27                 
28                 if(K&0x1)
29                 {
30                     _for(i,100,201)
31                     {
32                         if(hash[i])
33                         {
34                             hash[200-i]++;
35                             hash[i] --;
36                             break;
37                         }
38                     }
39                 }
40             }
41             else
42             {
43                 int index = 0;
44                 while(K --)
45                 {
46                     while(hash[index]==0)
47                         index ++;
48                     hash[index] --;
49                     hash[200-index] ++; 
50                 }
51             }
52 
53             int rnt = 0;
54             _for(i,0,201)
55             {
56                 rnt += hash[i] * (i-100);
57             }
58             return rnt;
59         }
60 };

分类讨论,随便乱搞过了

转载于:https://www.cnblogs.com/Asurudo/p/10504849.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值