当前位置:网站首页>Leetcode 1005 maximized array sum after K negations

Leetcode 1005 maximized array sum after K negations

2022-06-12 01:47:00 baj001

Ideas

Original link

  1. First step : The array from Sort small to large , So the minimum value is at the front
  2. The second step : Traverse back and forth , When you encounter a negative number, change it to a positive number , Judge this value ( minimum value ) The last number Is it smaller , If so, then idx++
  3. The third step : If K Greater than 0, that Repeatedly change the element with the lowest value , take K run out
  4. Step four : Sum up
class Solution {
    
    public int largestSumAfterKNegations(int[] A, int K) {
    
        if(A.length == 1) return K % 2 == 0 ? A[0] : -A[0];
        Arrays.sort(A);
        int sum = 0;
        int idx = 0;
        for(int i = 0; i < K; i++){
    
            // Don't take the last position , Because the last position is the largest 
            if(i < A.length - 1 && A[idx] < 0){
    
                A[idx] = -A[idx];
                if(A[idx] >= Math.abs(A[idx + 1])) idx++;
                // After jumping out of the loop , because idx already ++, Then enter again for when , The judgment is the next position 
                    continue; 
            }
   		// If no value is found to be less than 0 Of course. , In order to achieve k Secondary inversion , Only the current value can be manipulated ( Invert the current value ) 
            A[idx] = -A[idx];
        }
        // Statistics sum
        for(int i = 0; i < A.length; i++){
    
            sum += A[i];
        }
        return sum;
    }
}
原网站

版权声明
本文为[baj001]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203011216128120.html

随机推荐