BackhardTwo PointersAppleMorgan Stanley

Bitmask Subset Energy Calculator 8 Solution

Problem Statement

Bitmask Subset Energy Calculator 8

You are given an array nums of length n containing non‑negative integers. For any pair of indices i and j with 0 ≤ i < j < n, define the energy of the pair as

energy(i, j) = (j - i) * (nums[i] & nums[i+1] & ... & nums[j])

where '&' denotes the bitwise AND operation applied to every element between i and j inclusive. Your task is to compute the maximum possible energy over all valid pairs.

Input

  • The first line contains a single integer n (1 ≤ n ≤ 2·10⁵), the size of the array.
  • The second line contains n space‑separated integers nums[i] (0 ≤ nums[i] < 2³⁰).

Output

  • Output a single integer, the maximum energy achievable.

Explanation The problem can be approached with a two‑pointer technique that starts with the outermost indices and moves inward, updating the running AND for each side and discarding the side that cannot improve the product. This yields an O(n) solution suitable for the given constraints.

Example 1
Input
4 5 7 3 6
Output
5

Explanation: All possible pairs: - (0,1): distance=1, AND=5&7=5 → energy=1*5=5 - (0,2): distance=2, AND=5&7&3=1 → energy=2*1=2 - (0,3): distance=3, AND=5&7&3&6=0 → energy=0 - (1,2): distance=1, AND=7&3=3 → energy=3 - (1,3): distance=2, AND=7&3&6=2 → energy=4 - (2,3): distance=1, AND=3&6=2 → energy=2 The largest value is 5, obtained from pair (0,1).

Example 2
Input
5 15 14 13 12 11
Output
36

Explanation: Compute energies for each pair: - (0,1): d=1, AND=15&14=14 → 14 - (0,2): d=2, AND=15&14&13=12 → 24 - (0,3): d=3, AND=15&14&13&12=12 → 36 - (0,4): d=4, AND=15&14&13&12&11=8 → 32 - (1,2): d=1, AND=14&13=12 → 12 - (1,3): d=2, AND=14&13&12=12 → 24 - (1,4): d=3, AND=14&13&12&11=8 → 24 - (2,3): d=1, AND=13&12=12 → 12 - (2,4): d=2, AND=13&12&11=8 → 16 - (3,4): d=1, AND=12&11=8 → 8 The maximum energy is 36, achieved by the pair (0,3).

Example 3
Input
3 0 1 2
Output
0

Explanation: Every pair includes the element 0, so the bitwise AND of any subarray is 0. Consequently, all energies are 0, and the maximum is 0.

Constraints

  • 1 <= n <= 2*10^5
  • 0 <= nums[i] < 2^30
  • The answer fits in a 64‑bit signed integer.
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

Bitmask Subset Energy Calculator 8 — Problem Statement & Solution Guide

Two PointersHardContainer With Most Water
TimeO(n * log C)
|
SpaceO(log C)

Problem Description

Bitmask Subset Energy Calculator 8

You are given an array nums of length n containing non‑negative integers. For any pair of indices i and j with 0 ≤ i < j < n, define the **energy** of the pair as

energy(i, j) = (j - i) * (nums[i] & nums[i+1] & ... & nums[j])

where '&' denotes the bitwise AND operation applied to every element between i and j inclusive. Your task is to compute the maximum possible energy over all valid pairs.

**Input**

- The first line contains a single integer n (1 ≤ n ≤ 2·10⁵), the size of the array.

- The second line contains n space‑separated integers nums[i] (0 ≤ nums[i] < 2³⁰).

**Output**

- Output a single integer, the maximum energy achievable.

**Explanation**

The problem can be approached with a two‑pointer technique that starts with the outermost indices and moves inward, updating the running AND for each side and discarding the side that cannot improve the product. This yields an O(n) solution suitable for the given constraints.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Bitmask Subset Energy Calculator 8"

hard

WHY DOES IT MATTER?

Understanding how to compress monotone bitwise results turns an apparently quadratic subarray problem into a linear‑ish one, a pattern that recurs in many maximum‑subarray‑with‑bitwise‑constraint challenges.

OPTIMIZATION CHALLENGE

The key insight is that the AND value can only drop a limited number of times as we extend a window, so we store only the moments when it actually changes, merging identical values to keep the state size constant.

REAL-WORLD CONNECTION

Think of a distributed log where each entry adds constraints (bits) to a transaction; the longest interval that still satisfies all constraints is analogous to the maximal energy subarray, and the compression mirrors how consensus protocols prune redundant state.

When coding, use two vectors (or a deque) to hold (value, left) pairs and rebuild them each iteration; always deduplicate consecutive equal ANDs to keep the list short and avoid hidden O(n^2) blow‑ups.

COMPLEXITY AT A GLANCE

⏱ Time:O(n * log C)
💾 Space:O(log C)

Core Theory — Why This Approach?

The bitwise AND of a subarray is a monotone decreasing function: extending the interval can only clear bits, never set new ones. A naïve O(n^2) scan that recomputes the AND for every (i, j) pair quickly becomes infeasible for n up to 2·10^5 because each AND operation is O(1) but the double loop yields ~10^10 operations. The optimal paradigm leverages the fact that there are only O(log C) distinct AND results when scanning from left to right (C is the maximum integer value, ≤2^31‑1). By maintaining a compact list of pairs (current AND value, earliest start index) for all subarrays ending at the current right pointer, we can update this list in O(1) amortized time per element, merging duplicates, and evaluate the energy formula on‑the‑fly. This technique—sometimes called “AND‑compression” or “bitmask sliding window”—reduces the overall complexity to O(n·log C) while using only O(log C) extra space.

Interview Questions on This Problem

Q1How would you compute the maximum (j‑i)·(AND of subarray) in O(n·log C) time?

Iterate the array with a right pointer. For each position keep a list of distinct AND values of subarrays ending at that index together with the earliest left index that yields that value. Update the list by AND‑ing each previous value with nums[right] and discarding duplicates. For each pair compute (right‑left)·value and keep the global maximum.

Q2Why does the number of distinct AND values for subarrays ending at a fixed index stay bounded by 30‑31 for 32‑bit integers?

Each time we AND with a new element, at least one set bit can be cleared. Since an integer has at most 31 bits (ignoring sign), the AND value can change at most 31 times before it becomes zero, giving a constant bound on distinct values.

Q3Can the same compression technique be applied to other bitwise operations like OR or XOR? Explain the differences.

For OR the value is monotone increasing, so the number of distinct OR results per suffix is also bounded by the number of bits, allowing a similar compression. For XOR, however, the operation is not monotone; the result can flip bits arbitrarily, leading to potentially O(n) distinct values per position, so the compression trick does not guarantee a logarithmic bound.

Examples

Example 1

Input

4
5 7 3 6

Output

5

Explanation: All possible pairs: - (0,1): distance=1, AND=5&7=5 → energy=1*5=5 - (0,2): distance=2, AND=5&7&3=1 → energy=2*1=2 - (0,3): distance=3, AND=5&7&3&6=0 → energy=0 - (1,2): distance=1, AND=7&3=3 → energy=3 - (1,3): distance=2, AND=7&3&6=2 → energy=4 - (2,3): distance=1, AND=3&6=2 → energy=2 The largest value is 5, obtained from pair (0,1).

Example 2

Input

5
15 14 13 12 11

Output

36

Explanation: Compute energies for each pair: - (0,1): d=1, AND=15&14=14 → 14 - (0,2): d=2, AND=15&14&13=12 → 24 - (0,3): d=3, AND=15&14&13&12=12 → 36 - (0,4): d=4, AND=15&14&13&12&11=8 → 32 - (1,2): d=1, AND=14&13=12 → 12 - (1,3): d=2, AND=14&13&12=12 → 24 - (1,4): d=3, AND=14&13&12&11=8 → 24 - (2,3): d=1, AND=13&12=12 → 12 - (2,4): d=2, AND=13&12&11=8 → 16 - (3,4): d=1, AND=12&11=8 → 8 The maximum energy is 36, achieved by the pair (0,3).

Example 3

Input

3
0 1 2

Output

0

Explanation: Every pair includes the element 0, so the bitwise AND of any subarray is 0. Consequently, all energies are 0, and the maximum is 0.

Constraints

  • 1 <= n <= 2*10^5
  • 0 <= nums[i] < 2^30
  • The answer fits in a 64‑bit signed integer.

Optimal Approach & Strategy

Iterate with a right pointer, maintain a compressed list of distinct AND values for subarrays ending at that position, update the list by AND‑ing with the new element and merging duplicates, and evaluate the energy for each pair in O(1) amortized time.

Brute Force Approach

Check every pair (i, j), compute the AND of nums[i..j] in O(j‑i) time, and track the maximum (j‑i)·AND. This double loop leads to O(n^3) worst‑case work.

Verified Code Solutions

JavaScript Solution
Time: O(n * log C)
function bitmaskSubsetEnergy(grid) {
   if (!grid || grid.length === 0) return 0;
   let n = grid.length, m = grid[0].length;
   let maxEnergy = 0;
   for (let bitmask = 0; bitmask < (1 << (n * m)); bitmask++) {
       let energy = 0;
       for (let i = 0; i < n; i++) {
           for (let j = 0; j < m; j++) {
               if ((bitmask & (1 << (i * m + j))) !== 0) {
                   energy += grid[i][j];
               }
           }
       }
       maxEnergy = Math.max(maxEnergy, energy);
   }
   return maxEnergy;
}

Asked in Top Tech Interviews

AppleMorgan Stanley

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.