Leetcode-1005 Maximize Sum Of Array After K Negations(K 次取反後最大化的數組和)
阿新 • • 發佈:2019-03-10
return largest pre efi col urn spa arr ack
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 { 23hash[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 };
分類討論,隨便亂搞過了
Leetcode-1005 Maximize Sum Of Array After K Negations(K 次取反後最大化的數組和)