Largest Element in an Array after Merge Operations - Problem

You are given a 0-indexed array nums consisting of positive integers.

You can perform 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 largest element that you can possibly obtain in the final array after performing the merge operations optimally.

Input & Output

Example 1 — Basic Merging
$ Input: nums = [2,1,3,4]
Output: 10
💡 Note: Working right-to-left: Start with 4. Since 3 ≤ 4, merge to get 7. Since 1 ≤ 7, merge to get 8. Since 2 ≤ 8, merge to get 10. Final answer is 10.
Example 2 — Cannot Merge All
$ Input: nums = [5,3,3]
Output: 6
💡 Note: Start with 3. Since 3 ≤ 3, merge to get 6. Since 5 > 6, cannot merge. Maximum between 5 and 6 is 6.
Example 3 — Single Element
$ Input: nums = [1]
Output: 1
💡 Note: Only one element, so the maximum possible value is 1.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Merge Operations: Create Largest Possible ElementRule: Can merge nums[i] with nums[i+1] if nums[i] ≤ nums[i+1]2134Original Array: [2, 1, 3, 4]Merge all elements10Maximum Element: 2 + 1 + 3 + 4 = 10
Understanding the Visualization
1
Input Array
Array [2,1,3,4] with merge rule: left ≤ right
2
Valid Merges
Find positions where nums[i] ≤ nums[i+1]
3
Optimal Result
Maximum possible value after all beneficial merges
Key Takeaway
🎯 Key Insight: Process from right to left - each element can absorb all smaller elements to its left
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
23.4K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen