Maximum Sized Array Problem
Description
LeetCode Problem 3344.
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), where0 <= i, j, k < n.
Return the maximum possible value of n such that the sum of all elements in array A does not exceed s.
Example 1:
Input: s = 10
Output: 2
Explanation:
- Elements of the array A for n = 2:
- A[0][0][0] = 0 * (0 OR 0) = 0
- A[0][0][1] = 0 * (0 OR 1) = 0
- A[0][1][0] = 0 * (1 OR 0) = 0
- A[0][1][1] = 0 * (1 OR 1) = 0
- A[1][0][0] = 1 * (0 OR 0) = 0
- A[1][0][1] = 1 * (0 OR 1) = 1
- A[1][1][0] = 1 * (1 OR 0) = 1
- A[1][1][1] = 1 * (1 OR 1) = 1
- The total sum of the elements in array A is 3, which does not exceed 10, so the maximum possible value of n is 2.
Example 2:
Input: s = 0
Output: 1
Explanation:
- Elements of the array A for n = 1:
- A[0][0][0] = 0 * (0 OR 0) = 0
- The total sum of the elements in array A is 0, which does not exceed 0, so the maximum possible value of n is 1.
Constraints:
0 <= s <= 10^15
Solution
Approach: Precompute, then binary search
The sum of (i | j) * k over all 0 <= i, j, k < n splits into the sum over k, which is n(n - 1) / 2, times f[n], the sum of (i | j) over i, j < n. The answer grows only like the fifth root of s, so n is at most about 1330. Precompute f with f[i] = f[i - 1] + i + 2 * (sum over j < i of (i | j)): the new row and column of the square add each pair (i, j) with j < i twice, plus (i, i) once.
The total for size n is f[n - 1] * (n - 1) * n / 2. It increases with n, so binary search the largest n whose total is at most s. Use 64-bit or big integers because the totals reach about 10^16.
Complexity: O(M^2) preprocessing (M = 1330) and O(log M) per query.
mx = 1330
f = [0] * mx
for i in range(1, mx):
f[i] = f[i - 1] + i
for j in range(i):
f[i] += 2 * (i | j)
class Solution:
def maxSizedArray(self, s: int) -> int:
l, r = 1, mx
while l < r:
m = (l + r + 1) >> 1
if f[m - 1] * (m - 1) * m // 2 <= s:
l = m
else:
r = m - 1
return l