Find maximum value of the last element after reducing the array with given operations | C ++ implementation of the approach ; Function to return the maximized value ; Overall minimum absolute value of some element from the array ; Add all absolute values ; Count positive and negative elements ; Both positive and negative values are present ; Only positive or negative values are present ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_maximum_value ( int a [ ] , int n ) { int sum = 0 ; int minimum = INT_MAX ; int pos = 0 , neg = 0 ; for ( int i = 0 ; i < n ; i ++ ) { minimum = min ( minimum , abs ( a [ i ] ) ) ; sum += abs ( a [ i ] ) ; if ( a [ i ] >= 0 ) pos += 1 ; else neg += 1 ; } if ( pos > 0 && neg > 0 ) return sum ; return ( sum - 2 * minimum ) ; } int main ( ) { int a [ ] = { 5 , 4 , 6 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << find_maximum_value ( a , n ) ; return 0 ; }