LeetCode2789. 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

二、题解

class Solution {
public:
    long long maxArrayValue(vector<int>& nums) {
        int n = nums.size();
        long long sum = nums.back();
        for(int i = n - 2;i >= 0;i--){
            sum = nums[i] <= sum ? sum + nums[i] : nums[i];
        }
        return sum;
    }
};

相关推荐

  1. leetcode2719. 统计整数数目

    2024-03-15 20:56:01       34 阅读
  2. Leetcode2719. 统计整数数目

    2024-03-15 20:56:01       31 阅读
  3. leetcode-2719统计证书数目

    2024-03-15 20:56:01       40 阅读
  4. leetcode2739--总行驶距离

    2024-03-15 20:56:01       10 阅读
  5. LeetCode289. Game of Life

    2024-03-15 20:56:01       32 阅读
  6. Leetcode279.完全平方数

    2024-03-15 20:56:01       15 阅读
  7. LeetCode279 完全平方数

    2024-03-15 20:56:01       14 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-15 20:56:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-15 20:56:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-15 20:56:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-15 20:56:01       18 阅读

热门阅读

  1. Linux磁盘管理

    2024-03-15 20:56:01       16 阅读
  2. RK3568 Ubuntu解决无法制作SD卡的问题

    2024-03-15 20:56:01       17 阅读
  3. 【vue回调函数中的 this 指向上】

    2024-03-15 20:56:01       15 阅读
  4. C++ 预编译头文件

    2024-03-15 20:56:01       21 阅读
  5. Excel百万数据如何导入导出

    2024-03-15 20:56:01       19 阅读