C ++中的K取反后最大化数组和
问题陈述
给定大小为n且数字为k的数组。我们必须修改数组k次。
修改数组意味着在每个操作中我们可以通过取反来替换任何数组元素arr[i],即arr[i]=-arr[i]。该任务的执行方式是,在进行k次操作后,数组的总和必须最大。
如果输入arr[]={7,-3,5,4,-1},则最大和为20
首先取反-3。现在数组变成{7,3,5,4,-1}
取反-1。现在数组变成{7,3,5,4,1}
算法
1. Replace the minimum element arr[i] in array by -arr[i] for current operation 2. Once minimum element becomes 0, we don’t need to make any more changes. In this way we can make sum of array maximum after K operations
示例
#include <bits/stdc++.h> using namespace std; int getMaxSum(int *arr, int n, int k){ for (int i = 1; i <= k; ++i) { int minValue = INT_MAX; int index = -1; for (int j = 0; j < n; ++j) { if (arr[j] < minValue) { minValue = arr[j]; index = j; } } if (minValue == 0) { break; } arr[index] = -arr[index]; } int sum = 0; for (int i = 0; i < n; ++i) { sum = sum + arr[i]; } return sum; } int main(){ int arr[] = {7, -3, 5, 4, -1}; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << "Maximum sum = " << getMaxSum(arr, n, k) << endl; return 0; }
输出结果
当您编译并执行上述程序时。它产生以下输出&mnus;
Maximum sum = 20