Mid/SeniorArrayGreedy

Largest Element in an Array after Merge Operations

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]. Replace the element nums[i + 1] with nums[i] + nums[i + 1] and delete the element nums[i] from the array.

Return the value of the largest element that you can possibly obtain in the final array.

Example 1
Inputnums = [2,3,7,9,3]
Output21
The operations can produce [21, 3], so the largest element in the final array is 21, and no larger element can be obtained.
Example 2
Inputnums = [5,3,3]
Output11
After merging at i = 1 and then at i = 0, the final array is [11].

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^6

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate