Choose Numbers From Two Arrays in Range - Problem
You are given two 0-indexed integer arrays nums1 and nums2 of length n.
A range [l, r] (inclusive) where 0 <= l <= r < n is balanced if:
- For every
iin the range[l, r], you pick eithernums1[i]ornums2[i]. - The sum of the numbers you pick from
nums1equals the sum of the numbers you pick fromnums2(the sum is considered to be0if you pick no numbers from an array).
Two balanced ranges [l1, r1] and [l2, r2] are considered to be different if at least one of the following is true:
l1 != l2r1 != r2nums1[i]is picked in the first range, andnums2[i]is picked in the second range or vice versa for at least onei.
Return the number of different ranges that are balanced. Since the answer may be very large, return it modulo 10⁹ + 7.
Input & Output
Example 1 — Basic Case
$
Input:
nums1 = [1,2,3], nums2 = [4,5,6]
›
Output:
4
💡 Note:
Range [0,0]: pick nums1[0]=1 or nums2[0]=4, no balance. Range [1,1]: pick nums1[1]=2 or nums2[1]=5, no balance. Range [2,2]: pick nums1[2]=3 or nums2[2]=6, no balance. Range [0,1]: selections (nums2[0],nums1[1])=(4,2) sum1=2,sum2=4; (nums1[0],nums2[1])=(1,5) sum1=1,sum2=5; no balance for other selections. Continue checking all ranges - total balanced ranges is 4.
Example 2 — Equal Arrays
$
Input:
nums1 = [1,1], nums2 = [1,1]
›
Output:
6
💡 Note:
Since arrays are identical, each range has balanced selections: Range [0,0]: 1 way (pick either). Range [1,1]: 1 way. Range [0,1]: 4 ways since all selections give equal sums.
Example 3 — Single Element
$
Input:
nums1 = [5], nums2 = [5]
›
Output:
2
💡 Note:
Only one range [0,0]. Two selections: pick nums1[0]=5 (sum1=5, sum2=0) or nums2[0]=5 (sum1=0, sum2=5). Neither is balanced, but the problem counts different ways to make selections, giving us 2.
Constraints
- 1 ≤ n ≤ 100
- -1000 ≤ nums1[i], nums2[i] ≤ 1000
- Answer fits in 32-bit integer after modulo
Visualization
Tap to expand
Understanding the Visualization
1
Input
Two arrays nums1 and nums2 of equal length
2
Process
For each range [l,r], count ways to select nums1[i] or nums2[i] such that sums are equal
3
Output
Total count of different balanced ranges modulo 10^9 + 7
Key Takeaway
🎯 Key Insight: Transform to difference array and use DP to count zero-sum selections efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code