Minimum Sum of Values by Dividing Array - Problem

You are given two arrays nums and andValues of length n and m respectively.

The value of an array is equal to the last element of that array.

You have to divide nums into m disjoint contiguous subarrays such that for the i-th subarray [l_i, r_i], the bitwise AND of the subarray elements is equal to andValues[i].

In other words: nums[l_i] & nums[l_i + 1] & ... & nums[r_i] == andValues[i] for all 1 <= i <= m, where & represents the bitwise AND operator.

Return the minimum possible sum of the values of the m subarrays nums is divided into. If it is not possible to divide nums into m subarrays satisfying these conditions, return -1.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,4,3,3,2], andValues = [0,3,3,2]
Output: 12
💡 Note: Divide into [1,4], [3], [3], [2]. AND values: 1&4=0, 3=3, 3=3, 2=2. Sum of last elements: 4+3+3+2=12.
Example 2 — Impossible Case
$ Input: nums = [2,3,5,7,7,7,5], andValues = [0,7,5]
Output: -1
💡 Note: Cannot divide array into 3 subarrays with required AND values.
Example 3 — Single Elements
$ Input: nums = [1,2,3,4], andValues = [2]
Output: -1
💡 Note: No single subarray can have AND value of 2 from these elements.

Constraints

  • 1 ≤ n == nums.length ≤ 104
  • 1 ≤ m == andValues.length ≤ min(n, 10)
  • 1 ≤ nums[i] < 105
  • 0 ≤ andValues[i] < 105

Visualization

Tap to expand
Minimum Sum by Dividing Array with AND Constraintsnums = [1,4,3,3,2], andValues = [0,3,3,2]143321&4=0 ✓3=3 ✓3=3 ✓2=2 ✓Value: 4Value: 3Value: 3Value: 2Total Sum: 4 + 3 + 3 + 2 = 12All AND constraints satisfied!Result: 12
Understanding the Visualization
1
Input
Array [1,4,3,3,2] and AND values [0,3,3,2]
2
Process
Find valid divisions where each subarray AND matches required value
3
Output
Minimum sum of last elements: 12
Key Takeaway
🎯 Key Insight: Use DP to try all valid divisions where subarray AND values match requirements
Asked in
Google 12 Microsoft 8 Amazon 6
12.0K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen