Problem solving with programming: Finding equal sum index
Watson gives Sherlock an arrayA of length N . Then he asks him to determine if there exists an element in the array such that the sum of the elements on its left is equal to the sum of the elements on its right. If there are no elements to the left/right, then the sum is considered to be zero.
Formally, find ani , such that, A 1+A 2...A i-1 =A i+1+A i+2...A N.
Given an array of numbers, find an index such that the sum of numbers to the left is equal to the sum of elements to it's right. If there are no elements to the left or right, the sum is considered to be zero.
Now, for each index i, we can find the left sum in prefix_sum[i-1] and right sum intotal_sum - prefix_sum[i] which can be found in O(1) time. So this algorithm takes O(n)time.
Watson gives Sherlock an array
Formally, find an
Given an array of numbers, find an index such that the sum of numbers to the left is equal to the sum of elements to it's right. If there are no elements to the left or right, the sum is considered to be zero.
Now, for each index i, we can find the left sum in prefix_sum[i-1] and right sum intotal_sum - prefix_sum[i] which can be found in O(1) time. So this algorithm takes O(n)time.
Read full article from Problem solving with programming: Finding equal sum indexcin >> t;while( t-- ){int n;cin >> n;vector<int> nums(n);int i;for( i = 0; i < n; i++ ){cin >> nums[i];}vector<long long> prefixSum(n);if( n == 1 )cout << "YES" << endl;else{prefixSum[0] = nums[0];for( i = 1; i < n; i++ )prefixSum[i] = prefixSum[i-1]+nums[i];bool found = false;for( i = 1; i < n-1; i++ ){if (prefixSum[i-1] == prefixSum[n-1]-prefixSum[i]){found = true;break;}}if( found ){cout << "YES" << endl;}else{cout << "NO" << endl;}}}