Largest Element in an Array after Merge Operations — LeetCode 2789 Python Solution

MediumGreedyArray
Problem
#2789
Pattern
Greedy
Reading time
2 min

The problem

You are given a 0-indexed array nums consisting of positive integers. You can do the following operation on the array any number of times: Choose an index i such that 0 <= i < nums.length - 1 and nums[i] <= nums[i + 1].

Example

Input
nums = [2,3,7,9,3]
Output
21
Explanation
We can apply the following operations on the array:

Python solution

Python
class Solution:
    def maxArrayValue(self, nums: List[int]) -> int:
        for i in range(len(nums) - 2, -1, -1):
            if nums[i] <= nums[i + 1]:
                nums[i] += nums[i + 1]
        return max(nums)

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2789. Largest Element in an Array after Merge Operations is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2789. Largest Element in an Array after Merge Operations?
LeetCode 2789. Largest Element in an Array after Merge Operations is rated Medium on LeetCode.
What is the time complexity of LeetCode 2789. Largest Element in an Array after Merge Operations?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 2789. Largest Element in an Array after Merge Operations?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2789. Largest Element in an Array after Merge Operations cover?
LeetCode 2789. Largest Element in an Array after Merge Operations is tagged Greedy and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview