

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- Maximize Sum Of Array After K Negations in Python
- Maximize the median of the given array after adding K elements to the same array in C++
- Program to maximize the minimum value after increasing K sublists in Python
- Maximum array sum that can be obtained after exactly k changes in C++
- Maximize the maximum subarray sum after removing at most one element in C++
- Maximize the number of sum pairs which are divisible by K in C++
- Array sum after dividing numbers from previous?
- Maximize the subarray sum after multiplying all elements of any subarray with X in C++
- Maximize the sum of array by multiplying prefix of array with -1 in C++
- Negation logic in SAP ABAP
- Array sum after dividing numbers from previous in C?
- Maximize the size of array by deleting exactly k sub-arrays to make array prime in C++
- Program to find maximize score after n operations in Python
- Find the Initial Array from given array after range sum queries in C++
- Maximize the sum of arr[i]*i in C++
Advertisements