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 - Mathematical Formula INPUT 3D Array A[i][j][k] = i * (j OR k) n x n x n A[i][j][k] = i * (j OR k) where 0 <= i,j,k < n Input: s s = 6 Sum(A) <= s Find max n ALGORITHM STEPS 1 Derive Sum Formula Sum = f(n) using OR properties 2 Binary Search n Search range [1, upper_bound] 3 Test n values Calculate sum for each n 4 Find max valid n Where sum <= s Testing n values: n Sum Valid? 1 0 OK 2 2 OK 3 18 NO 18 > 6, invalid FINAL RESULT 0 0 0 1 2 x 2 x 2 array visualization Output n = 2 Verification: Sum = 2 <= 6 OK - Maximum n found! Key Insight: The sum formula can be derived mathematically: Sum = (n*(n-1)/2) * (sum of (j OR k) for all j,k). Using binary search on n with this formula gives O(log n) solution instead of O(n^3) brute force. For s=6: n=2 gives sum=2 (valid), n=3 gives sum=18 (exceeds 6), so maximum n=2. TutorialsPoint - Maximum Sized Array | Mathematical Formula Approach
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