#2640

Find the Score of All Prefixes of an Array

Medium
ArrayPrefix SumPrefix SumDynamic Programming
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)

By maintaining a running maximum and using it to compute scores incrementally, we can avoid redundant calculations and achieve a linear time complexity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an empty result array 'ans' and a variable 'max_so_far' to track the maximum value seen so far.
  2. 2Step 2: Iterate through the nums array, updating 'max_so_far' with the maximum value at each index.
  3. 3Step 3: For each index 'i', calculate ans[i] as ans[i-1] + nums[i] + max_so_far, handling the first index separately.
solution.py10 lines
1# Full working Python code
2
3def findPrefixScores(nums):
4    n = len(nums)
5    ans = [0] * n
6    max_so_far = 0
7    for i in range(n):
8        max_so_far = max(max_so_far, nums[i])
9        ans[i] = (ans[i - 1] + nums[i] + max_so_far) if i > 0 else (nums[i] + max_so_far)
10    return ans

Complexity note: This complexity is linear because we only traverse the input array once, maintaining the maximum and calculating scores incrementally.

  • 1Keep track of the maximum value seen so far to optimize calculations.
  • 2Use cumulative sums to build results incrementally instead of recalculating.

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