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 long prefix = 0;
    int maxi = 0;

    for (const int num : nums) {
      maxi = max(maxi, num);
      prefix += num + maxi;
      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 max = 0;

    for (int i = 0; i < nums.length; i++) {
      max = Math.max(max, nums[i]);
      prefix += nums[i] + max;
      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 = []
    maxi = 0

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

    return itertools.accumulate(conver)