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 of Values by Dividing Array INPUT nums array: 1 4 3 3 2 indices: 0 1 2 3 4 andValues array: 0 3 3 2 Goal: Divide nums into m=4 subarrays where AND of each subarray equals corresponding andValues[i] Minimize: sum of last elements of each subarray (subarray value = last element) ALGORITHM STEPS 1 DP with Memoization dp(i,j,curr) = min sum from index i, subarray j, AND=curr 2 Find Valid Splits Try each position where cumulative AND = andValues[j] 3 Track AND Values Maintain running AND, prune when impossible 4 Compute Min Sum Return min total of all subarray last elements Optimal Division: [1,4] AND = 0, val = 4 [3] AND = 3, val = 3 [3] AND = 3, val = 3 [2] AND = 2, val = 2 Sum = 4 + 3 + 3 + 2 = 12 FINAL RESULT Array Division: [1, 4] AND=0, val=4 [3] AND=3, val=3 [3] AND=3, val=3 [2] AND=2 Calculation: 4 + 3 + 3 + 2 = 12 OUTPUT 12 OK - Valid division found Minimum sum achieved Key Insight: Use DP with memoization: dp(i, j, currentAND) tracks minimum sum to complete division starting from index i, needing j more subarrays, with running AND value. AND operation only decreases or stays same, enabling early pruning when currentAND becomes less than target andValues[j]. TutorialsPoint - Minimum Sum of Values by Dividing Array | Optimal Solution
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