In its general version, this problem imposes 2 limitations, and this can be done in a simpler way.
- If the section can only be done somewhere along the length of the array (we do not consider elements out of order)
- No negative numbers.
The algorithm, which then works, could be:
- Have 2 variables, leftSum and rightSum
- Start increasing leftSum to the left and rightSum to the right of the array.
- Try to correct any imbalance.
The following code does the following:
public boolean canBalance(int[] nums) { int leftSum = 0, rightSum = 0, i, j; if(nums.length == 1) return false; for(i=0, j=nums.length-1; i<=j ;){ if(leftSum <= rightSum){ leftSum+=nums[i]; i++; }else{ rightSum+=nums[j]; j--; } } return (rightSum == leftSum); }
Exit:
canBalance({1, 1, 1, 2, 1}) β true OK canBalance({2, 1, 1, 2, 1}) β false OK canBalance({10, 10}) β true OK canBalance({1, 1, 1, 1, 4}) β true OK canBalance({2, 1, 1, 1, 4}) β false OK canBalance({2, 3, 4, 1, 2}) β false OK canBalance({1, 2, 3, 1, 0, 2, 3}) β true OK canBalance({1, 2, 3, 1, 0, 1, 3}) β false OK canBalance({1}) β false OK canBalance({1, 1, 1, 2, 1}) β true OK
Of course, if the elements can be combined out of order, it turns into a partition problem with all its complexity.