LeetCode 1802: Maximum Value at a Given Index in a Bounded Array Solution

Master LeetCode problem 1802 (Maximum Value at a Given Index in a Bounded Array), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1802. Maximum Value at a Given Index in a Bounded Array

Problem Explanation

Explanation:

To maximize the value at the given index while satisfying the constraints, we can use binary search to find the maximum possible value at that index. We can then calculate the sum of the elements before and after the index to ensure that the total sum does not exceed maxSum. Based on this, we adjust the binary search range accordingly.

  1. Perform binary search to find the maximum value at the given index.
  2. Calculate the sum of elements before and after the index.
  3. Adjust the binary search range based on the total sum.
  4. Return the maximum value at the given index.

Time Complexity: O(log(maxSum)) Space Complexity: O(1)

:

Solution Code

class Solution {
    public int maxValue(int n, int index, int maxSum) {
        int left = 1, right = maxSum;
        while (left < right) {
            int mid = left + (right - left) / 2;
            long sum = calculateSum(n, index, mid);
            if (sum < maxSum) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left;
    }
    
    private long calculateSum(int n, int index, int num) {
        long sum = num;
        int left = Math.min(index, num - 1);
        int right = Math.min(n - index - 1, num - 1);
        sum += (long)left * (left + 1) / 2 + (long)right * (right + 1) / 2;
        return sum;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1802 (Maximum Value at a Given Index in a Bounded Array)?

This page provides optimized solutions for LeetCode problem 1802 (Maximum Value at a Given Index in a Bounded Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1802 (Maximum Value at a Given Index in a Bounded Array)?

The time complexity for LeetCode 1802 (Maximum Value at a Given Index in a Bounded Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1802 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1802 in Java, C++, or Python.

Back to LeetCode Solutions