Find the Score of All Prefixes of an Array - 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.

Given a 0-indexed integer array nums of length n, return an array ans of length n where ans[i] is the score of the prefix nums[0..i].

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,3,4]
Output: [4,7,13,21]
💡 Note: For prefix [2]: max=2, conversion=[2+2]=[4], score=4. For prefix [2,1]: conversion=[2+2,1+2]=[4,3], score=7. For prefix [2,1,3]: conversion=[2+2,1+2,3+3]=[4,3,6], score=13. For prefix [2,1,3,4]: conversion=[2+2,1+2,3+3,4+4]=[4,3,6,8], score=21.
Example 2 — Increasing Array
$ Input: nums = [1,3,6,4,5]
Output: [2,8,20,28,38]
💡 Note: For prefix [1]: conversion=[2], score=2. For prefix [1,3]: conversion=[2,6], score=8. For prefix [1,3,6]: conversion=[2,6,12], score=20. Each element gets added to the running maximum at its position.
Example 3 — Decreasing Array
$ Input: nums = [5,4,3,2,1]
Output: [10,19,27,34,40]
💡 Note: Maximum stays at 5 throughout, so conversion array for each prefix: [5]→[10], [5,4]→[10,9], [5,4,3]→[10,9,8], etc. Prefix scores are cumulative sums of conversion arrays.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -106 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Find the Score of All Prefixes INPUT nums array: 2 i=0 1 i=1 3 i=2 4 i=3 Definitions: conver[i] = arr[i] + max(arr[0..i]) score = sum of conver array ans[i] = score of prefix nums[0..i] For prefix [2,1,3]: conver[0] = 2 + max(2) = 4 conver[1] = 1 + max(2,1) = 3 conver[2] = 3 + max(2,1,3) = 6 score = 4 + 3 + 6 = 13? No, 15! (We need cumulative approach) ALGORITHM STEPS 1 Initialize maxVal = 0, score = 0 2 Update maxVal maxVal = max(maxVal, nums[i]) 3 Add to score score += nums[i] + maxVal 4 Store result ans[i] = score Trace: i n[i] max score 0 2 2 4 1 1 2 7 2 3 3 15 3 4 4 31 FINAL RESULT ans array: [4, 7, 15, 31] Breakdown: ans[0] = 4 ans[1] = 7 ans[2] = 15 ans[3] = 31 Complexity: Time: O(n) Space: O(n) for output OK Key Insight: The score of prefix[0..i] = score of prefix[0..i-1] + nums[i] + max(nums[0..i]). We accumulate score incrementally while tracking running maximum. No need to recompute! TutorialsPoint - Find the Score of All Prefixes of an Array | One Pass Solution
Asked in
Google 25 Amazon 18 Microsoft 15
23.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen