โ† Back to Index

๐Ÿ“š Maximum Value at a Given Index in a Bounded Array โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Maximum Value at a Given Index in a Bounded Array problem involves constructing an array of size n such that the sum of its elements does not exceed maxSum, and the value at a specific index index is maximized. The array values must be positive integers, and the difference between adjacent elements must not exceed 1.

๐Ÿงฑ Pattern Template

class Solution {
    public int maxValue(int n, int index, int maxSum) {
        int left = 1, right = maxSum;

        while (left < right) {
            int mid = (left + right + 1) / 2;

            if (isValid(n, index, maxSum, mid)) {
                left = mid; // Try a larger value
            } else {
                right = mid - 1; // Try a smaller value
            }
        }

        return left;
    }

    private boolean isValid(int n, int index, int maxSum, int value) {
        long sum = value;

        // Calculate left side sum
        if (index > 0) {
            int leftCount = index;
            int leftSum = (value > leftCount) 
                ? (long) (value - 1 + value - leftCount) * leftCount / 2
                : (long) (value - 1 + 1) * value / 2;
            sum += leftSum;
        }

        // Calculate right side sum
        if (index < n - 1) {
            int rightCount = n - index - 1;
            int rightSum = (value > rightCount) 
                ? (long) (value - 1 + value - rightCount) * rightCount / 2
                : (long) (value - 1 + 1) * value / 2;
            sum += rightSum;
        }

        return sum <= maxSum;
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Maximum Value at a Given Index

Input: n = 4, index = 2, maxSum = 6
Output: 2

Explanation:
- The array [1, 2, 2, 1] satisfies the constraints.
- The maximum value at index 2 is 2.

๐Ÿ’ก Pro Tips