Dynamic Programming21 sections · 916 units
Open in Course

Assignment - key observation

Process in order

Here's the trick: process nums1 in order, from index 00 to n1n-1. When assigning nums1[kk], you've already assigned indices 00 to k1k-1. The mask tells you which elements of nums2 are taken. The number of set bits equals how many nums1 elements have been assigned.

So popcount(mask) tells you which nums1 index comes next. This eliminates the need for a second dimension. You don't need dp[mask][i]dp[\text{mask}][i] because i=popcount(mask)i = \text{popcount}(\text{mask}).