Skip to main content
Back to problems
#2789
Medium Algorithms

Largest element in an array after merge operations

Array Greedy
47.6% acceptance
Feb 25, 2026
500
33
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn max_array_value(nums: Vec<i32>) -> i64 {
    let n = nums.len();
    let mut total = nums[n - 1] as i64;
    for i in (0..n - 1).rev() {
      if nums[i] as i64 <= total {
        total += nums[i] as i64;
      } else {
        total = nums[i] as i64;
      }
    }
    total
  }
}