Problem
We define the conversion array conver
of an array arr
as follows:
conver[i] = arr[i] + max(arr[0..i])
wheremax(arr[0..i])
is the maximum value ofarr[j]
over0 <= 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 arrayans
of lengthn
whereans[i]
is the score of the prefix
nums[0..i]
.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
Solution
Method 1 – Prefix Maximum and Prefix Sum
Intuition
For each prefix nums[0..i], the conversion array is defined as conver[j] = nums[j] + max(nums[0..j]). The score of the prefix is the sum of conver[0..i]. We can maintain the running maximum and running sum to compute the answer efficiently.
Approach
- Initialize max_so_far = 0, sum_so_far = 0, ans = [].
- For each index i from 0 to n-1:
- Update max_so_far = max(max_so_far, nums[i]).
- Add nums[i] + max_so_far to sum_so_far.
- Append sum_so_far to ans.
- Return ans.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
— One pass through the array. - 🧺 Space complexity:
O(n)
— For the output array.