Skip to content

2640. Find the Score of All Prefixes of an Array 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  vector<long long> findPrefixScore(vector<int>& nums) {
    vector<long long> ans;
    long prefix = 0;
    int mx = 0;

    for (const int num : nums) {
      mx = max(mx, num);
      prefix += num + mx;
      ans.push_back(prefix);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public long[] findPrefixScore(int[] nums) {
    long[] ans = new long[nums.length];
    long prefix = 0;
    int mx = 0;

    for (int i = 0; i < nums.length; i++) {
      mx = Math.max(mx, nums[i]);
      prefix += nums[i] + mx;
      ans[i] = prefix;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def findPrefixScore(self, nums: list[int]) -> list[int]:
    conver = []
    mx = 0

    for num in nums:
      mx = max(mx, num)
      conver.append(num + mx)

    return itertools.accumulate(conver)