Taro Logo

Maximum Array Hopping Score I

Medium
Asked by:
Zluri
0 views
Topics:
ArraysDynamic ProgrammingGreedy Algorithms

Given an array nums, you have to get the maximum score starting from index 0 and hopping until you reach the last element of the array.

In each hop, you can jump from index i to an index j > i, and you get a score of (j - i) * nums[j].

Return the maximum score you can get.

Example 1:

Input: nums = [1,5,8]

Output: 16

Explanation:

There are two possible ways to reach the last element:

  • 0 -> 1 -> 2 with a score of (1 - 0) * 5 + (2 - 1) * 8 = 13.
  • 0 -> 2 with a score of (2 - 0) * 8 = 16.

Example 2:

Input: nums = [4,5,2,8,9,1,3]

Output: 42

Explanation:

We can do the hopping 0 -> 4 -> 6 with a score of (4 - 0) * 9 + (6 - 4) * 3 = 42.

Constraints:

  • 2 <= nums.length <= 103
  • 1 <= nums[i] <= 105

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can we hop from any position to *any* subsequent position, or is the jump distance restricted by the value at the current position?
  2. How is the score for a hop calculated? Is it strictly based on the distance between indices multiplied by the destination value, or is there another formula?
  3. What should be returned if the array has only a single element, or if it's not possible to reach the end of the array?
  4. Can the array contain negative numbers or zeros, and how do they affect the score accumulation?
  5. Are we required to end our hops precisely at the last index of the array, or is landing on or past the last index sufficient?

Brute Force Solution

Approach

Imagine you are standing in a line of numbered tiles and you want to hop your way forward while collecting the maximum possible points. The brute force approach works by stubbornly trying out every single combination of hops possible from start to finish.

Here's how the algorithm would work step-by-step:

  1. Begin your journey at the very first tile.
  2. Look at all the other tiles ahead of you and pick one to hop to.
  3. Once you land on that new tile, calculate the points you earned for that hop and add it to your total score.
  4. From your current tile, look ahead again and pick another tile to hop to, continuing this process until you physically cannot hop any further because you reached the end.
  5. Every time you successfully make it to the final tile, write down your total accumulated score.
  6. Now, go back and repeat the entire hopping journey, but this time make a different sequence of choices at every single turn.
  7. Keep doing this until you have explored every possible path of hops from the starting tile to the end.
  8. Finally, look back at all your written scores and pick the highest one as your ultimate winning result.

Code Implementation

def max_score_brute_force(tiles):
    # We define a recursive helper to explore every possible hopping path and calculate all scores
    def explore_paths(current_index, current_score):
        if current_index >= len(tiles) - 1:
            return current_score

        maximum_total_score = 0

        # We iterate through all subsequent tiles to try every possible branch of the decision tree
        for next_tile_index in range(current_index + 1, len(tiles)):
            hop_score = (next_tile_index - current_index) * tiles[next_tile_index]
            total_path_score = explore_paths(next_tile_index, current_score + hop_score)
            if total_path_score > maximum_total_score:
                maximum_total_score = total_path_score

        return maximum_total_score

    # We kick off the exhaustive search starting from the very first tile with an initial score of zero
    return explore_paths(0, 0)

Big(O) Analysis

Time Complexity
O(n²) – For each of n tiles in the array, the brute force approach recursively tries hopping to every single remaining tile ahead of it to explore all possible paths. At the first tile we branch out to n-1 choices, at the second tile to n-2 choices, and so on down the line. This nested exploration of every combination leads to approximately n * n/2 operations, which simplifies to O(n²).
Space Complexity
O(1) – To determine the maximum score while trying out every single combination of hops, the algorithm only needs a few primitive scalar variables to track the current index, running score, and maximum score found so far. No auxiliary data structures, temporary lists, hash maps, or recursive call stacks are utilized during this exhaustive exploration. Therefore, the extra memory consumed remains entirely constant regardless of the input array size N.

Optimal Solution

Approach

The problem asks for the maximum score to reach the last element by hopping forward, where each hop from index i to j awards (j - i) * nums[j]. Each unit step between index 0 and the final index contributes nums[j] to the total score, where j is the next hop landing point. Thus, for each unit interval, we greedily pick the maximum element that lies to its right.

Here's how the algorithm would work step-by-step:

  1. Initialize total_score to zero and current_max to zero.
  2. Traverse the array from the last index down to index 1.
  3. Update current_max whenever the current element is greater than the previous suffix maximum.
  4. Accumulate current_max into total_score for each unit segment.
  5. Return the accumulated total_score once all segments down to index 0 are processed.

Code Implementation

def max_score(nums: list[int]) -> int:
    total_score = 0
    current_max = 0
    # Iterate backwards through the array to find the optimal hop target.
    for index in range(len(nums) - 1, 0, -1):
        # Keep track of the suffix maximum value seen so far.
        if nums[index] > current_max:
            current_max = nums[index]
        # Add the maximum reachable multiplier for each unit step.
        total_score += current_max
    return total_score

Big(O) Analysis

Time Complexity
O(n) – We traverse the array of length n once from right to left, performing constant-time comparisons and additions at each step.
Space Complexity
O(1) – Only a few scalar variables are used to maintain the running maximum and total score, requiring no additional dynamic memory.

Edge Cases

Empty or null input array
How to Handle:
Check for null or empty arrays at the start and return a score of zero immediately.
Single element array
How to Handle:
Return a score of zero since no hops can be made from the starting position to a subsequent position.
Array with only two elements
How to Handle:
Compute the direct score from the first element to the second element and return it as the only option.
Array containing zeros at intermediate positions
How to Handle:
The algorithm should correctly calculate hop distances and scores even when landing on or jumping from zero values.
Strictly decreasing array values
How to Handle:
Ensure the dynamic programming or greedy approach properly evaluates all intermediate hops to find the optimal path.
Extremely large array size causing performance bottlenecks
How to Handle:
Implement an O(n) or O(n squared) solution that avoids deep recursion and optimizes state transitions to scale efficiently.
Large integer values causing arithmetic overflow
How to Handle:
Use 64-bit integer types for score accumulation to prevent overflow during cumulative additions.
All identical values across the array
How to Handle:
The algorithm naturally evaluates skipping intermediate steps versus taking consecutive steps to maximize the total score.