partition-equal-subset-sum.sh — zsh
dynamic-programmingarrays

Given an integer array nums, return true if you can split it into two subsets whose sums are equal, or false otherwise. Every element must belong to exactly one of the two subsets.

Input / output

  • Input: nums: int[]
  • Output: boolean

Examples

  1. nums = [1,5,11,5] returns true because [1,5,5] and [11] both sum to 11.
  2. nums = [1,2,3,5] returns false; no split gives two equal halves.
  3. nums = [1,1] returns true.

Constraints

  • 1 <= nums.length <= 200
  • 1 <= nums[i] <= 100

Follow-up Notice that if the total is odd the answer is immediately false. Once you target sum / 2, why is it safe to iterate the inner sums from high to low with a single boolean row?

Examples
Example 1
Input: nums = [1,5,11,5]
Output: true
Example 2
Input: nums = [1,2,3,5]
Output: false
Example 3
Input: nums = [1,1]
Output: true