BackhardDynamic ProgrammingMetaUber

Hyper-Dimensional Grid Optimizer 4 Solution

Problem Statement

You are given an integer M (1 ≤ M ≤ 20) describing the number of binary dimensions and an integer N (1 ≤ N ≤ 2^M) representing the count of weighted points in this M‑dimensional hyper‑grid. Each point i is described by a pair (mask_i, val_i) where mask_i is an integer in the range [0, 2^M‑1] encoding the coordinates of the point as an M‑bit mask and val_i (‑10^9 ≤ val_i ≤ 10^9) is its weight. For every mask X from 0 to 2^M‑1 you must compute the maximum total weight obtainable by selecting any subset of the given points such that each selected point’s mask is a submask of X (i.e., (mask_i & X) == mask_i). Points with negative weight may be omitted because the subset is optional. Output the result for all masks in increasing order, separated by a single space.

Example 1
Input
2 3 0 5 1 3 2 7
Output
5 8 12 15

Explanation: M=2 gives masks 00,01,10,11. For mask 00 only point (0,5) fits → 5. For mask 01 points (0,5) and (1,3) fit, both are non‑negative, sum = 8. For mask 10 points (0,5) and (2,7) fit → 12. For mask 11 all three points fit → 5+3+7 = 15.

Example 2
Input
3 4 3 4 5 -2 6 6 7 1
Output
0 0 0 4 0 0 6 11

Explanation: M=3 produces masks 000‑111. Positive‑valued points are (3,4), (6,6) and (7,1); the point (5,‑2) is ignored because it lowers the sum. For each target mask we add the values of all positive points whose mask is a submask: - 000,001,010 have no fitting positive points → 0. - 011 includes mask 3 → 4. - 100,101 have no positive submask → 0. - 110 includes mask 6 → 6. - 111 includes masks 3,6,7 → 4+6+1 = 11. Thus the sequence is 0 0 0 4 0 0 6 11.

Example 3
Input
4 5 8 10 3 5 12 -3 15 7 0 2
Output
2 2 2 7 2 2 2 7 12 12 12 17 12 12 12 24

Explanation: M=4 gives 16 masks. Positive points are (0,2), (3,5), (8,10) and (15,7); the point (12,‑3) is never taken. For each mask we sum the values of all positive points that are submasks: - Masks 0‑2 contain only (0,2) → 2. - Mask 3 adds (3,5) → 2+5 = 7. - Masks 4‑6 again only have (0,2) → 2. - Mask 7 inherits mask 3’s set → 7. - Masks 8‑10 contain (0,2) and (8,10) → 12. - Mask 11 adds (3,5) to the previous set → 2+5+10 = 17. - Masks 12‑14 could include (12,‑3) but we skip it, leaving the same total as masks 8‑10 → 12. - Mask 15 includes all positive points → 2+5+10+7 = 24. The ordered results match the output string.

Constraints

  • 1 ≤ M ≤ 20
  • 1 ≤ N ≤ 2^M
  • 0 ≤ mask_i < 2^M
  • -10^9 ≤ val_i ≤ 10^9
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Hyper-Dimensional Grid Optimizer 4 — Problem Statement & Solution Guide

Dynamic ProgrammingHardSOS DP
TimeO(M·2^M)
|
SpaceO(2^M)

Problem Description

You are given an integer M (1 ≤ M ≤ 20) describing the number of binary dimensions and an integer N (1 ≤ N ≤ 2^M) representing the count of weighted points in this M‑dimensional hyper‑grid. Each point i is described by a pair (mask_i, val_i) where mask_i is an integer in the range [0, 2^M‑1] encoding the coordinates of the point as an M‑bit mask and val_i (‑10^9 ≤ val_i ≤ 10^9) is its weight. For every mask X from 0 to 2^M‑1 you must compute the maximum total weight obtainable by selecting any subset of the given points such that each selected point’s mask is a submask of X (i.e., (mask_i & X) == mask_i). Points with negative weight may be omitted because the subset is optional. Output the result for all masks in increasing order, separated by a single space.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Hyper-Dimensional Grid Optimizer 4"

hard

WHY DOES IT MATTER?

Bitmask DP and SOS DP let you exploit the exponential structure of subsets without enumerating them, turning otherwise intractable combinatorial explosions into linear‑in‑the‑state‑space solutions. This pattern appears in many optimization problems on subsets, such as traveling salesman, set cover variants, and XOR‑based queries.

OPTIMIZATION CHALLENGE

The key insight is that the relationship between a mask and its sub‑masks is regular: flipping a single bit moves you to a neighboring node in the hyper‑cube. By iterating over bits and updating in‑place, you collapse M nested loops over subsets into M linear sweeps over the entire 2^M state space.

REAL-WORLD CONNECTION

Think of a distributed cache where each node stores a feature flag (bit). To answer "what is the best configuration that includes a given set of flags?" you propagate the best known configuration from smaller flag sets to larger ones, exactly like SOS DP propagates values across the hyper‑grid.

When coding SOS DP, always use an iterative in‑place update (for i in 0..M‑1, for mask in 0..(1<<M)-1) and check the bit with (mask & (1<<i)). This avoids extra memory and keeps cache locality high, which is crucial for passing tight time limits.

COMPLEXITY AT A GLANCE

⏱ Time:O(M·2^M)
💾 Space:O(2^M)

Core Theory — Why This Approach?

The problem lives on an M‑dimensional Boolean hyper‑grid, where each point is encoded as an M‑bit mask. A naïve solution would enumerate every subset of the N points, compute the combined mask and sum of values, and keep the best feasible configuration – this costs O(2^N) time and is impossible when N can be as large as 2^M (≈1,048,576 for M=20). The optimal paradigm is a bitmask dynamic programming technique often called SOS (Sum‑Over‑Subsets) DP. By storing the best achievable value for every possible mask (size 2^M) and propagating information from sub‑masks to supersets (or vice‑versa) in M passes, we can compute the answer in O(M·2^M) time. The DP recurrence typically looks like dp[mask] = max(dp[mask], dp[mask ^ (1<<i)]) for each bit i, which efficiently aggregates contributions of points whose masks are subsets of the current mask. This transforms an exponential‑in‑N brute force into a pseudo‑polynomial algorithm bounded by the hyper‑grid size, which is tractable for M ≤ 20.

Interview Questions on This Problem

Q1How would you compute, for every mask, the maximum total weight of points whose masks are subsets of that mask?

Initialize dp[mask] with the weight of the point exactly matching mask (or -∞ if none). Then run SOS DP: for each bit i from 0 to M‑1, for every mask, if mask has bit i set, update dp[mask] = max(dp[mask], dp[mask ^ (1<<i)]). After M passes dp[mask] holds the optimum for all subsets.

Q2Why does a naïve O(N·2^M) enumeration of all masks fail when M=20 and N≈2^M?

Because N·2^M ≈ (2^20)·(2^20)=2^40 ≈ 1 trillion operations, far exceeding typical time limits. The constant factor of iterating over every point for every mask makes the algorithm infeasible, whereas SOS DP reduces the factor to M, yielding roughly 20·2^20 ≈ 20 million operations.

Q3In a distributed system, how could you parallelize the SOS DP computation for a 20‑bit hyper‑grid?

Since each SOS pass updates dp[mask] based only on dp[mask ^ (1<<i)] from the previous pass, you can assign disjoint ranges of masks to different workers for each bit iteration. After each pass, a barrier synchronizes workers before proceeding to the next bit, ensuring data consistency while achieving near‑linear speed‑up.

Examples

Example 1

Input

2
3
0 5
1 3
2 7

Output

5 8 12 15

Explanation: M=2 gives masks 00,01,10,11. For mask 00 only point (0,5) fits → 5. For mask 01 points (0,5) and (1,3) fit, both are non‑negative, sum = 8. For mask 10 points (0,5) and (2,7) fit → 12. For mask 11 all three points fit → 5+3+7 = 15.

Example 2

Input

3
4
3 4
5 -2
6 6
7 1

Output

0 0 0 4 0 0 6 11

Explanation: M=3 produces masks 000‑111. Positive‑valued points are (3,4), (6,6) and (7,1); the point (5,‑2) is ignored because it lowers the sum. For each target mask we add the values of all positive points whose mask is a submask: - 000,001,010 have no fitting positive points → 0. - 011 includes mask 3 → 4. - 100,101 have no positive submask → 0. - 110 includes mask 6 → 6. - 111 includes masks 3,6,7 → 4+6+1 = 11. Thus the sequence is 0 0 0 4 0 0 6 11.

Example 3

Input

4
5
8 10
3 5
12 -3
15 7
0 2

Output

2 2 2 7 2 2 2 7 12 12 12 17 12 12 12 24

Explanation: M=4 gives 16 masks. Positive points are (0,2), (3,5), (8,10) and (15,7); the point (12,‑3) is never taken. For each mask we sum the values of all positive points that are submasks: - Masks 0‑2 contain only (0,2) → 2. - Mask 3 adds (3,5) → 2+5 = 7. - Masks 4‑6 again only have (0,2) → 2. - Mask 7 inherits mask 3’s set → 7. - Masks 8‑10 contain (0,2) and (8,10) → 12. - Mask 11 adds (3,5) to the previous set → 2+5+10 = 17. - Masks 12‑14 could include (12,‑3) but we skip it, leaving the same total as masks 8‑10 → 12. - Mask 15 includes all positive points → 2+5+10+7 = 24. The ordered results match the output string.

Constraints

  • 1 ≤ M ≤ 20
  • 1 ≤ N ≤ 2^M
  • 0 ≤ mask_i < 2^M
  • -10^9 ≤ val_i ≤ 10^9

Optimal Approach & Strategy

Use SOS DP to propagate the best weight from each mask to all supersets in M passes, achieving O(M·2^M) time.

Brute Force Approach

Enumerate every subset of the N points, compute the union mask and total weight, and keep the maximum feasible value.

Verified Code Solutions

JavaScript Solution
Time: O(M·2^M)
function solution(grid) {
   const n = grid.length;
   const prefixSum = Array(n + 1).fill(0).map(() => Array(n + 1).fill(0));
   for (let i = 1; i <= n; i++) {
       for (let j = 1; j <= n; j++) {
           prefixSum[i][j] = prefixSum[i - 1][j] + prefixSum[i][j - 1] - prefixSum[i - 1][j - 1] + grid[i - 1][j - 1];
       }
   }
   let maxSum = -Infinity;
   for (let i = 1; i <= n; i++) {
       for (let j = 1; j <= n; j++) {
           for (let k = i; k <= n; k++) {
               for (let l = j; l <= n; l++) {
                   maxSum = Math.max(maxSum, prefixSum[k][l] - prefixSum[i - 1][l] - prefixSum[k][j - 1] + prefixSum[i - 1][j - 1]);
               }
           }
       }
   }
   return maxSum;
}

Asked in Top Tech Interviews

MetaUber

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.