Find the Score of All Prefixes of an Array - Problem
Imagine you're analyzing stock prices where you want to understand the cumulative impact of each day's performance combined with the peak performance seen so far.
Given an array nums, we need to calculate a special conversion score for each prefix of the array. For any prefix ending at index i, the conversion formula is:
conversion[i] = nums[i] + max(nums[0..i])
This means we add the current element to the maximum element we've seen so far in that prefix.
The score of a prefix is the sum of all conversion values in that prefix. Your task is to return an array where result[i] represents the score of the prefix nums[0..i].
Example: For nums = [2, 3, 7, 5, 4]
- Prefix [2]: conversion = [2+2] = [4], score = 4
- Prefix [2,3]: conversion = [2+3, 3+3] = [5,6], score = 11
- Prefix [2,3,7]: conversion = [2+7, 3+7, 7+7] = [9,10,14], score = 33
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [2, 3, 7, 5, 4]
โบ
Output:
[4, 10, 24, 36, 46]
๐ก Note:
Prefix [2]: max=2, conversion=[4], score=4. Prefix [2,3]: max=3, conversion=[5,6], score=11. Wait, that's wrong. Let me recalculate: Prefix [2,3]: max=3, conversion=[2+3,3+3]=[5,6], score=11. But the expected output shows 10. Let me check: the score should be cumulative sum of conversions. Actually, for [2,3,7,5,4]: scores are [4,11,33,50,66]. The pattern suggests score[i] = previous_score + (nums[i] + current_max).
example_2.py โ Single Element
$
Input:
nums = [5]
โบ
Output:
[10]
๐ก Note:
For single element array, the prefix [5] has max=5, conversion=[5+5]=[10], so score=10.
example_3.py โ Decreasing Array
$
Input:
nums = [10, 5, 2, 1]
โบ
Output:
[20, 35, 47, 58]
๐ก Note:
Maximum stays 10 throughout. Prefix [10]: score=20. Prefix [10,5]: score=20+15=35. Prefix [10,5,2]: score=35+12=47. Prefix [10,5,2,1]: score=47+11=58.
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 109
- Follow up: Can you solve this in O(n) time and O(1) extra space?
Visualization
Tap to expand
Understanding the Visualization
1
Initialize State
Start with running_max=0 and cumulative_score=0
2
Process Each Element
Update running maximum and add (element + max) to cumulative score
3
Store Results
The cumulative score at each step is the answer for that prefix
Key Takeaway
๐ฏ Key Insight: By maintaining running maximum and cumulative score, we avoid recalculating the same values repeatedly, transforming an O(nยฒ) problem into an elegant O(n) solution.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code