Maximum Sized Array - Problem

Given a positive integer s, let A be a 3D array of dimensions n × n × n, where each element A[i][j][k] is defined as:

A[i][j][k] = i * (j OR k)

where 0 <= i, j, k < n and OR is the bitwise OR operation.

Return the maximum possible value of n such that the sum of all elements in array A does not exceed s.

Input & Output

Example 1 — Small Budget
$ Input: s = 6
Output: 2
💡 Note: For n=2: sum = 0*(0|0) + 0*(0|1) + 0*(1|0) + 0*(1|1) + 1*(0|0) + 1*(0|1) + 1*(1|0) + 1*(1|1) = 0+0+0+0+0+1+1+1 = 3. For n=3: sum would be much larger. So maximum n=2.
Example 2 — Larger Budget
$ Input: s = 100
Output: 4
💡 Note: For n=4, the sum of all A[i][j][k] = i*(j|k) values is within budget 100, but n=5 would exceed it.
Example 3 — Minimum Case
$ Input: s = 0
Output: 1
💡 Note: For n=1: only A[0][0][0] = 0*(0|0) = 0, so sum=0 ≤ 0. For n=2, sum=3 > 0. Maximum n=1.

Constraints

  • 1 ≤ s ≤ 109
  • The answer n will be at most 104

Visualization

Tap to expand
Maximum Sized Array: A[i][j][k] = i * (j OR k)3D Array (n×n×n)A[0][0][0] = 0*(0|0) = 0A[1][0][1] = 1*(0|1) = 1A[1][1][1] = 1*(1|1) = 1...Sum ConstraintSum of all elements ≤ sFind maximum nthat satisfies constraintBinary SearchO(log²n) timeEfficient solutionfor large inputsExample: s=6 → n=2 (sum=3), s=100 → n=4As n increases, sum grows rapidly due to i*(j OR k) formulaKey: Use mathematical formula + binary search for optimal O(log²n) solution
Understanding the Visualization
1
3D Array
Each A[i][j][k] = i * (j OR k)
2
Sum Constraint
Find max n where total sum ≤ s
3
Binary Search
Efficiently find the answer
Key Takeaway
🎯 Key Insight: The sum is monotonically increasing with n, enabling binary search on the answer space for optimal efficiency
Asked in
Google 25 Facebook 18 Microsoft 15 Amazon 12
23.4K Views
Medium Frequency
~35 min Avg. Time
892 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