#2789

Largest Element in an Array after Merge Operations

specialist · 910 · lc medium +31 · verified · 47.7% accepted · 500 likes · top 33%

Description

A 0-indexed array nums of positive integers is given. You may apply the following operation any number of times:

- Choose index i with 0 <= i < nums.length - 1 and nums[i] <= nums[i + 1]. Replace nums[i + 1] with nums[i] + nums[i + 1] and remove nums[i].

Return the largest element obtainable in the final array.

Example 1:

Input: nums = [2,3,7,9,3]
Output: 21
Explanation: We can apply the following operations on the array:
- Choose i = 0. The resulting array will be nums = [5,7,9,3].
- Choose i = 1. The resulting array will be nums = [5,16,3].
- Choose i = 0. The resulting array will be nums = [21,3].
The largest element in the final array is 21. It can be shown that we cannot obtain a larger element.

Example 2:

Input: nums = [5,3,3]
Output: 11
Explanation: We can do the following operations on the array:
- Choose i = 1. The resulting array will be nums = [5,6].
- Choose i = 0. The resulting array will be nums = [11].
There is only one element in the final array, which is 11.

Code

1
2
3