There is an array consisting of (2 * n – 1) integers. We can change sign of exactly n elements in the array. In other words, we can select exactly n array elements, and multiply each of them by -1. Find the maximum sum of the array.
Input : arr = 50 50 50 Output : 150 There is no need to change anything. The sum of elements equals 150 which is maximum. Input : arr = -1 -100 -1 Output : 100 Change the sign of the first two elements. Sum of the elements equal to 100.
Step 1:- Iterate the loop for 2*n-1 times and repeat the steps 2, 3 and 4.
Step 2:- Calculate no. of negative numbers (neg).
Step 3:- Calculate the sum (sum) of the array by taking absolute values of the numbers.
Step 4:- Find the minimum number of the array by taking absolute values of the numbers (min).
Step 5:- Check if the no. of negative numbers is odd and the value of n (given) is even then subtract two times m from the sum and this will be max_sum of the array else, the value of sum will be the max_sum of the array.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Given an array A and a number x, check for pair in A with sum as x
- Search an element in a sorted and rotated array
- Merge an array of size n into another array of size m+n
- k largest(or smallest) elements in an array | added Min Heap method
- Program for array rotation
- Write a program to reverse an array or string
- Reversal algorithm for array rotation
- Block swap algorithm for array rotation
- Leaders in an array
- Count Inversions in an array | Set 1 (Using Merge Sort)
- Find the smallest and second smallest elements in an array
- Maximum and minimum of an array using minimum number of comparisons
- Check for Majority Element in a sorted array
- Segregate 0s and 1s in an array
- Ceiling in a sorted array
Improved By : vt_m