[LeetCode] 2789. 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 integer 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:
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.

Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 106

合并后数组中的最大元素。

给你一个下标从 0 开始、由正整数组成的数组 nums 。

你可以在数组上执行下述操作 任意 次:
选中一个同时满足 0 <= i < nums.length - 1 和 nums[i] <= nums[i + 1] 的整数 i 。将元素 nums[i + 1] 替换为 nums[i] + nums[i + 1] ,并从数组中删除元素 nums[i] 。

返回你可以从最终数组中获得的 最大 元素的值。

思路

思路是贪心。对于数组中的元素,只有满足 nums[i] <= nums[i + 1] 的时候,才能将 nums[i + 1] 替换为 nums[i] + nums[i + 1],那么比较自然的想法是可以从数组的最右侧开始往左扫描,如果发现某个元素 nums[i] >= nums[i - 1],就可以将 nums[i] 累加到 nums[i - 1] 上。这里我用一个变量 sum 来统计过程中能找到的最大的累加和。如果发现某个元素 nums[i] > sum,则说明从右往左扫的时候需要在这里停下,sum 要从 nums[i] 开始重新统计。

复杂度

时间O(n)
空间O(1)

代码

Java实现

class Solution {
    public long maxArrayValue(int[] nums) {
        int n = nums.length;
        long sum = nums[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            if (sum >= nums[i]) {
                sum += (long) nums[i];
            } else {
                sum = (long) nums[i];
            }
        }
        return sum;
    }
}
posted @ 2024-03-14 15:41  CNoodle  阅读(18)  评论(0编辑  收藏  举报