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; }
输出
编译并执行上述程序时,它会生成以下输出:
Maximum sum = 20
广告