Smallest indexed array element required to be flipped to make sum of array equal to 0 | C ++ program to implement the above approach ; Function to find the smallest indexed array element required to be flipped to make sum of the given array equal to 0 ; Stores the required index ; Traverse the given array ; Flip the sign of current element ; Stores the sum of array elements ; Find the sum of the array ; Update sum ; If sum is equal to 0 ; Update pos ; Reset the current element to its original value ; Reset the value of arr [ i ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestIndexArrayElementsFlip ( int arr [ ] , int N ) { int pos = -1 ; for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] *= -1 ; int sum = 0 ; for ( int j = 0 ; j < N ; j ++ ) { sum += arr [ j ] ; } if ( sum == 0 ) { pos = i ; break ; } else { arr [ i ] *= -1 ; } } return pos ; } int main ( ) { int arr [ ] = { 1 , 3 , -5 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << smallestIndexArrayElementsFlip ( arr , N ) ; return 0 ; }