Count number of ways to divide an array into two halves with same sum | C ++ program to count the number of ways to divide an array into two halves with the same sum ; Function to count the number of ways to divide an array into two halves with same sum ; if length of array is 1 answer will be 0 as we have to split it into two non - empty halves ; variables to store total sum , current sum and count ; finding total sum ; checking if sum equals total_sum / 2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cntWays ( int arr [ ] , int n ) { if ( n == 1 ) return 0 ; int tot_sum = 0 , sum = 0 , ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) tot_sum += arr [ i ] ; for ( int i = 0 ; i < n - 1 ; i ++ ) { sum += arr [ i ] ; if ( sum == tot_sum / 2 ) ans ++ ; } return ans ; } int main ( ) { int arr [ ] = { 1 , -1 , 1 , -1 , 1 , -1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << cntWays ( arr , n ) ; return 0 ; }