Problem 395325 · medium · Phase 03 Linear Management & Searching

Fewest Merges to Make a Palindrome

two pointers · greedy

You are given a list of positive integers nums. In one operation you may replace two adjacent elements by their sum (the list gets one element shorter). Return the minimum number of operations needed until the list reads the same forwards and backwards.

Examples

Input:  nums = [1, 4, 3, 2]
Output: 2
Explanation: merge 1+4 -> [5, 3, 2], then merge 3+2 -> [5, 5].

Input:  nums = [1, 2, 3, 2, 1]
Output: 0

Constraints

  • 0 <= len(nums) <= 10**5, 1 <= nums[i] <= 10**6
  • Target: O(n) time, O(1) extra space.

Goals

  • Compare running sums from both ends instead of single elements
  • Grow the smaller side greedily and argue why that is optimal
Starting Python…