Leetcode 1005. Maximize Sum Of Array After K Negations

Problem Description:

Given an array A of integers, we must modify the array in the following way: we choose an i and replace A[i] with -A[i], and we repeat this process K times in total.  (We may choose the same index i multiple times.)

Return the largest possible sum of the array after modifying it in this way.

 

这道题leetcode标的难度是easy,其实要是想不到好的思路的话会有很多麻烦要处理,自己开始想到的解法要修改数组A,而且提交了几次才通过。看了discuss里一个从来没见过的黑人小哥的代码太棒了,分享一下。

这个解法充分利用了优先数组。

public int largestSumAfterKNegations(int[] A, int K) {
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
        
        for(int x: A) pq.add(x);
        while( K--  > 0) pq.add(-pq.poll());
  
        int sum  = 0;
        for(int i = 0; i < A.length; i++){
            sum += pq.poll();
        }
        return sum;
    }

 

posted @ 2019-03-11 13:17  起点菜鸟  阅读(324)  评论(0编辑  收藏  举报