Find the Score of All Prefixes of an Array — LeetCode 2640 Python Solution

MediumArrayPrefix Sum
Problem
#2640
Pattern
Prefix Sum
Reading time
2 min

The problem

We define the conversion array conver of an array arr as follows: conver[i] = arr[i] + max(arr[0..i]) where max(arr[0..i]) is the maximum value of arr[j] over 0 <= j <= i. We also define the score of an array arr as the sum of the values of the conversion array of arr.

Example

Input
nums = [2,3,7,5,10]
Output
[4,10,24,36,56]
Explanation
For the prefix [2], the conversion array is [4] hence the score is 4

Python solution

Python
class Solution:
    def findPrefixScore(self, nums: List[int]) -> List[int]:
        n = len(nums)
        ans = [0] * n
        mx = 0
        for i, x in enumerate(nums):
            mx = max(mx, x)
            ans[i] = x + mx + (0 if i == 0 else ans[i - 1])
        return ans

Complexity

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

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2640. Find the Score of All Prefixes of an Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2640. Find the Score of All Prefixes of an Array?
LeetCode 2640. Find the Score of All Prefixes of an Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 2640. Find the Score of All Prefixes of an Array?
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 2640. Find the Score of All Prefixes of an Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2640. Find the Score of All Prefixes of an Array cover?
LeetCode 2640. Find the Score of All Prefixes of an Array is tagged Array and Prefix Sum 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