📌  相关文章
📜  K个求反后最大化数组和|套装2

📅  最后修改于: 2021-04-29 12:06:58             🧑  作者: Mango

给定大小为n且数字为k的数组。我们必须修改数组K的次数。这里修改数组意味着在每个操作中我们都可以用-arr [i]替换任何数组元素arr [i]。我们需要以这样的方式执行此操作:在进行K次操作之后,数组的总和必须最大吗?

例子:

Input : arr[] = {-2, 0, 5, -1, 2} 
        K = 4
Output: 10
// Replace (-2) by -(-2), array becomes {2, 0, 5, -1, 2}
// Replace (-1) by -(-1), array becomes {2, 0, 5, 1, 2}
// Replace (0) by -(0), array becomes {2, 0, 5, 1, 2}
// Replace (0) by -(0), array becomes {2, 0, 5, 1, 2}

Input : arr[] = {9, 8, 8, 5} 
        K = 3
Output: 20

我们强烈建议您单击此处并进行实践,然后再继续解决方案。

我们在下面的文章中讨论了O(nk)解决方案。
K个求反后最大化数组和|套装1
上面文章中使用的想法是用-arr [i]替换数组中的最小元素arr [i]用于当前操作。这样,我们可以使K次运算后的数组总和最大。一旦出现有趣的情况,一旦最小元素变为0,我们就无需再进行任何更改。
以上解决方案中使用的实现使用线性搜索来找到最小元素。上述解决方案的时间复杂度为O(nk)
在本文中,实现了一种优化的解决方案,该解决方案使用优先级队列(或二进制堆)来快速查找最小元素。

以下是该想法的实现。它使用Java的PriorityQueue类。

C++
// A PriorityQueue based C++ program to
// maximize array sum after k negations.
#include 
using namespace std;
 
// Function to find Maximum sum
// after K negations
int MaxSum(int a[], int n, int k)
{
    int sum = 0;
     
    // Create a min heap for priority queue
    priority_queue, greater> pq;
 
    // Insert all elements in f array in priority_queue
    for(int i = 0; i < n; i++)
    {
        pq.push(a[i]);
    }
 
    while (k--)
    {
         
        // Retrieve and remove min element
        int temp = pq.top();
 
        pq.pop();
         
        // Modify the minimum element and
        // add back to priority queue
        temp = (temp) * -1;
        pq.push(temp);
    }
     
    // Calculate the sum
    while (!pq.empty())
    {
        sum = sum + pq.top();
        pq.pop();
    }
    return sum;
}
 
// Driver Code
int main()
{
    int a[] = { -2, 0, 5, -1, 2 };
    int n = sizeof(a) / sizeof(a[0]);
    int k = 4;
 
    cout << MaxSum(a, n, k);
    return 0;
}
 
// This code is contributed by Harshit Srivastava


Java
// A PriorityQueue based Java program to maximize array
// sum after k negations.
import java.util.*;
 
class maximizeSum
{
    public static int maxSum(int[] a, int k)
    {
        // Create a priority queue and insert all array elements
        // int
        PriorityQueue pq = new PriorityQueue<>();
        for (int x : a)
            pq.add(x);
 
        // Do k negations by removing a minimum element k times
        while (k-- > 0)
        {
            // Retrieve and remove min element
            int temp = pq.poll();
 
            // Modify the minimum element and add back
            // to priority queue
            temp *= -1;
            pq.add(temp);
        }
 
        // Compute sum of all elements in priority queue.
        int sum = 0;
        for (int x : pq)
            sum += x;
        return sum;
    }
 
    // Driver code
    public static void main (String[] args)
    {
        int[] arr = {-2, 0, 5, -1, 2};
        int k = 4;
        System.out.println(maxSum(arr, k));
    }
}


输出:

10