[LeetCode] Find the Score of All Prefixes of an Array

2640. Find the Score of All Prefixes of an Array

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].

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
vector<long long> findPrefixScore(vector<int>& nums) {
int ma = 0;
vector<long long> pre;
for(auto n : nums) {
ma = max(ma, n);
pre.push_back((pre.size() ? pre.back() : 0) + ma + n);
}
return pre;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/01/PS/LeetCode/find-the-score-of-all-prefixes-of-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.