Maximum Value at a Given Index in a Bounded Array — LeetCode 1802 Python Solution
- Problem
- #1802
- Pattern
- Monotonic Stack
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given three positive integers: n, index, and maxSum. You want to construct an array nums (0-indexed) that satisfies the following conditions: nums.length == n nums[i] is a positive integer where 0 <= i < n.
Example
- Input
- n = 4, index = 2, maxSum = 6
- Output
- 2
- Explanation
- nums = [1,2,2,1] is one array that satisfies all the conditions.
Python solution
class Solution:
def maxValue(self, n: int, index: int, maxSum: int) -> int:
def sum(x, cnt):
return (
(x + x - cnt + 1) * cnt // 2 if x >= cnt else (x + 1) * x // 2 + cnt - x
)
left, right = 1, maxSum
while left < right:
mid = (left + right + 1) >> 1
if sum(mid - 1, index) + sum(mid, n - index) <= maxSum:
left = mid
else:
right = mid - 1
return leftComplexity
| Measure | Complexity |
|---|---|
| Time | O(\log M), where M=maxSum |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 1802. Maximum Value at a Given Index in a Bounded Array is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1802. Maximum Value at a Given Index in a Bounded Array?
- LeetCode 1802. Maximum Value at a Given Index in a Bounded Array is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1802. Maximum Value at a Given Index in a Bounded Array?
- The Python solution on this page runs in O(\log M), where M=maxSum.
- What is the space complexity of LeetCode 1802. Maximum Value at a Given Index in a Bounded Array?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1802. Maximum Value at a Given Index in a Bounded Array cover?
- LeetCode 1802. Maximum Value at a Given Index in a Bounded Array is tagged Greedy, Math and Binary Search on LeetCode.