Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Maximize array sum after K negation in C++
Problem statement
Given an array of size n and a number k. We have to modify an array k number of times.
Modify array means in each operation we can replace any array element arr[i] by negating it i.e. arr[i] = -arr[i]. The task is to perform this operation in such a way that after k operations, the sum of an array must be maximum.
If input arr[] = {7, -3, 5, 4, -1} then maximum sum will be 20
- First negate -3. Now array becomes {7, 3, 5, 4, -1}
- Negate -1. Now array becomes {7, 3, 5, 4, 1}
Algorithm
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
Example
#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;
}
Output
When you compile and execute above program. It generates following output &mnus;
Maximum sum = 20
Advertisements
