Ctrl K

Balanced Cuts After One Replacement

Hard
You are given an integer array weights of length n. A **cut** after the first c elements (1 ≤ c ≤ n − 1) is balanced if the sum of those first c elements equals the sum of the rest. Before counting, you may replace **at most one** element of the array with the number spare (or change nothing). Return the largest possible number of balanced cuts.
Example 1
weights=[3, 1, 2, 4], spare=6 → 1

Without a change the cuts give 3|7, 4|6, 6|4, none balanced. Replacing 4 with 6 gives [3, 1, 2, 6], and the cut 3 + 1 + 2 | 6 balances 6 = 6. No change yields more than one balanced cut.

Example 2
weights=[2, -2, 2, -2, 0], spare=9 → 2

The array sums to 0. The cuts after the second and after the fourth element give 0 = 0, that is 2, and no replacement does better.

Example 3
weights=[5, 5], spare=1 → 1

The only cut, 5 | 5, is already balanced.

Constraints
  • 2 ≤ n ≤ 10⁵
  • -10⁵ ≤ weights[i], spare ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwins Within Two Swaps HardPump Rods at Their Peak HardPair GCDs by Sorted Position HardMatching Ends per Range MediumPrimes Along Grid Rays Medium
loading Python…
Input
weights=[3, 1, 2, 4], spare=6
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 116 tests on the server, hidden ones included.