Leetcode|Simple|1005. The sum of the arrays maximized after K inversions (twice greedy)

Insert picture description here

1 Twice Greedy

Considering these situations

1.1 K <= A.size()

  • + + + + + K + +++++K+ +++++ K + , the first element isK % 2addedaccording topositive and negative, the others can be added up
  • − − − − − K − -----K- K ,take the negativesum of[0, K - 1]all, and accumulate the others
  • − − K − + + + --K-+++ K+++ , WhenK < =负数个数the second step is done
  • − − − − + K + + ----+K++ +K++ , WhenK > 负数个数, the negative number is summed up, and the positive number is done according to the first step

1.2 K > A.size()

  • + + + + + + + +++++++ +++++++ , Same as the first in the previous step
  • − − − − − − − ------- , The first element isK % 2added upaccording to theplus and minus, the others are取负added up
  • − − K − + + + --K-+++ K+++ , Thenegative part is taken positive andaccumulated and追踪最小绝对值compared when the first positive number is reached, ①If the former is small and the remaining K will be placed, then subtract 2 times the minimum value and add the current positive number, and then accumulate; ② If the latter is small, and the remaining K will place an order, the positive number isK % 2added upaccording to theplus and minus, and the others are added up
  • − − − − + K + + ----+K++ +K++ , Same as the fourth step in the previous step

But in fact, sorting by absolute value from largest to smallest, you can achieve the above situation with only a small amount of judgment. The specific code is as follows

class Solution {
    
    
private:
    static bool cmp(int a, int b) {
    
    
        return abs(a) > abs(b);
    }
public:
    int largestSumAfterKNegations(vector<int>& A, int K) {
    
    
        // 1.按绝对值从大到小排列
        sort(A.begin(), A.end(), cmp);
        int sum = 0;
        for (auto& num : A) {
    
    
            // 2.负值变正
            if (num < 0 && K > 0) {
    
    
                num *= -1;
                K--;
            }
            sum += num;
        }
        // 3.处理K > A.size()情况
        if (K > 0 && K % 2 == 1) sum -= 2 * A[A.size() - 1];
        return sum;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/SL_World/article/details/114851450