#3282

Reach End of Array With Max Score

Medium
ArrayGreedyGreedyStack
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a greedy approach to jump to the next index that gives the highest score based on the hint provided. This reduces unnecessary calculations and focuses on the most promising jumps.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a variable to keep track of the maximum score.
  2. 2Step 2: Use a loop to iterate through the array, maintaining a stack to store indices of potential jumps.
  3. 3Step 3: For each index, pop from the stack while the current number is greater than the number at the index stored in the stack, calculating scores as you go.
  4. 4Step 4: Push the current index onto the stack and continue until reaching the last index.
solution.py15 lines
1# Full working Python code
2
3def maxScore(nums):
4    n = len(nums)
5    max_score = 0
6    stack = []
7    for i in range(n):
8        while stack and nums[stack[-1]] < nums[i]:
9            j = stack.pop()
10            max_score = max(max_score, (i - j) * nums[j])
11        stack.append(i)
12    return max_score
13
14# Example usage:
15print(maxScore([1, 3, 1, 5]))  # Output: 7

Complexity note: This complexity is due to the single pass through the array with a stack that may store up to n elements in the worst case.

  • 1From each index, the optimal jump is to the nearest index with a higher value.
  • 2Using a stack helps efficiently track potential jump indices and calculate scores.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.