Skip to content

2789. Largest Element in an Array after Merge Operations 👍

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

    for (int i = nums.size() - 2; i >= 0; --i)
      if (nums[i] > ans)
        ans = nums[i];
      else
        ans += nums[i];

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public long maxArrayValue(int[] nums) {
    long ans = nums[nums.length - 1];

    for (int i = nums.length - 2; i >= 0; --i)
      if (nums[i] > ans)
        ans = nums[i];
      else
        ans += nums[i];

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

    for i in range(len(nums) - 2, -1, -1):
      if nums[i] > ans:
        ans = nums[i]
      else:
        ans += nums[i]

    return ans