Visit Array Positions to Maximize Score — LeetCode 2786 Python Solution

MediumArrayDynamic Programming
Problem
#2786
Reading time
2 min

The problem

You are given a 0-indexed integer array nums and a positive integer x. You are initially at position 0 in the array and you can visit other positions according to the following rules: If you are currently in position i, then you can move to any position j such that i < j.

Example

Input
nums = [2,3,6,1,9,2], x = 5
Output
13
Explanation
We can visit the following positions in the array: 0 -> 2 -> 3 -> 4.

Python solution

Python
class Solution:
    def maxScore(self, nums: List[int], x: int) -> int:
        f = [-inf] * 2
        f[nums[0] & 1] = nums[0]
        for v in nums[1:]:
            f[v & 1] = max(f[v & 1], f[v & 1 ^ 1] - x) + v
        return max(f)

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array nums
SpaceO(1) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2786. Visit Array Positions to Maximize Score is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2786. Visit Array Positions to Maximize Score?
LeetCode 2786. Visit Array Positions to Maximize Score is rated Medium on LeetCode.
What is the time complexity of LeetCode 2786. Visit Array Positions to Maximize Score?
The Python solution on this page runs in O(n), where n is the length of the array nums.
What is the space complexity of LeetCode 2786. Visit Array Positions to Maximize Score?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2786. Visit Array Positions to Maximize Score cover?
LeetCode 2786. Visit Array Positions to Maximize Score is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview