返回介绍

solution / 1500-1599 / 1526.Minimum Number of Increments on Subarrays to Form a Target Array / README_EN

发布于 2024-06-17 01:03:18 字数 3970 浏览 0 评论 0 收藏 0

1526. Minimum Number of Increments on Subarrays to Form a Target Array

中文文档

Description

You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros.

In one operation you can choose any subarray from initial and increment each value by one.

Return _the minimum number of operations to form a _target_ array from _initial.

The test cases are generated so that the answer fits in a 32-bit integer.

 

Example 1:

Input: target = [1,2,3,2,1]
Output: 3
Explanation: We need at least 3 operations to form the target array from the initial array.
[0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).
[1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).
[1,2,2,2,1] increment 1 at index 2.
[1,2,3,2,1] target array is formed.

Example 2:

Input: target = [3,1,1,2]
Output: 4
Explanation: [0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2]

Example 3:

Input: target = [3,1,5,4,2]
Output: 7
Explanation: [0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2].

 

Constraints:

  • 1 <= target.length <= 105
  • 1 <= target[i] <= 105

Solutions

Solution 1

class Solution:
  def minNumberOperations(self, target: List[int]) -> int:
    return target[0] + sum(max(0, b - a) for a, b in pairwise(target))
class Solution {
  public int minNumberOperations(int[] target) {
    int f = target[0];
    for (int i = 1; i < target.length; ++i) {
      if (target[i] > target[i - 1]) {
        f += target[i] - target[i - 1];
      }
    }
    return f;
  }
}
class Solution {
public:
  int minNumberOperations(vector<int>& target) {
    int f = target[0];
    for (int i = 1; i < target.size(); ++i) {
      if (target[i] > target[i - 1]) {
        f += target[i] - target[i - 1];
      }
    }
    return f;
  }
};
func minNumberOperations(target []int) int {
  f := target[0]
  for i, x := range target[1:] {
    if x > target[i] {
      f += x - target[i]
    }
  }
  return f
}
function minNumberOperations(target: number[]): number {
  let f = target[0];
  for (let i = 1; i < target.length; ++i) {
    if (target[i] > target[i - 1]) {
      f += target[i] - target[i - 1];
    }
  }
  return f;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文