leetcode

Split Array With Minimum Difference - Link

Question Description

You are given a 0-indexed integer array nums of length n.

Split the array into two non-empty parts such that:

The difference between the two parts is the absolute difference between the sum of the left part and the sum of the right part.

Return the minimum difference possible between the two parts.


Constraints


Approach

Why this approach works:

Alternative approaches considered:


Dry Run

Example Input: nums = [2, 3, 1]

Step-by-step execution:

Final Answer = 2

Example Input: nums = [1, 2, 3, 4]

Step-by-step execution:

Final Answer = 2


Solution

class Solution {
    public long splitArray(int[] nums) {
        int n = nums.length;

        // prefix sums + strictly increasing check
        boolean[] left = new boolean[n];
        long[] leftSum = new long[n];
        left[0] = true;
        leftSum[0] = nums[0];
        for (int i = 1; i < n; i++) {
            left[i] = left[i - 1] && nums[i - 1] < nums[i];
            leftSum[i] = leftSum[i - 1] + nums[i];
        }

        // suffix sums + strictly decreasing check
        boolean[] right = new boolean[n];
        long[] rightSum = new long[n];
        right[n - 1] = true;
        rightSum[n - 1] = nums[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            right[i] = right[i + 1] && nums[i] > nums[i + 1];
            rightSum[i] = rightSum[i + 1] + nums[i];
        }

        // evaluate all splits
        long min = Long.MAX_VALUE;
        boolean found = false;
        for (int i = 0; i < n - 1; i++) {
            if (left[i] && right[i + 1]) {
                min = Math.min(min, Math.abs(leftSum[i] - rightSum[i + 1]));
                found = true;
            }
        }

        return found ? min : -1;
    }
}

Time and Space Complexity