Skip to content

2219. Maximum Sum Score of Array 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  long long maximumSumScore(vector<int>& nums) {
    long ans = LONG_MIN;
    long prefix = 0;
    long sum = accumulate(nums.begin(), nums.end(), 0L);

    for (const int num : nums) {
      prefix += num;
      ans = max({ans, prefix, sum - prefix + num});
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public long maximumSumScore(int[] nums) {
    long ans = Long.MIN_VALUE;
    long prefix = 0;
    long sum = Arrays.stream(nums).asLongStream().sum();

    for (final int num : nums) {
      prefix += num;
      ans = Math.max(ans, Math.max(prefix, sum - prefix + num));
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def maximumSumScore(self, nums: list[int]) -> int:
    ans = -math.inf
    prefix = 0
    summ = sum(nums)

    for num in nums:
      prefix += num
      ans = max(ans, prefix, summ - prefix + num)

    return ans