1827:最少操作使数组递增

This commit is contained in:
huangge1199 2021-06-07 11:33:29 +08:00
parent e8bbaeddaa
commit 7dd35f6164
2 changed files with 116 additions and 0 deletions

View File

@ -0,0 +1,73 @@
//给你一个整数数组 nums 下标从 0 开始每一次操作中你可以选择数组中一个元素并将它增加 1
//
//
// 比方说如果 nums = [1,2,3] 你可以选择增加 nums[1] 得到 nums = [1,3,3]
//
//
// 请你返回使 nums 严格递增 最少 操作次数
//
// 我们称数组 nums 严格递增的 当它满足对于所有的 0 <= i < nums.length - 1 都有 nums[i] < nums[i+1]
// 一个长度为 1 的数组是严格递增的一种特殊情况
//
//
//
// 示例 1
//
// 输入nums = [1,1,1]
//输出3
//解释你可以进行如下操作
//1) 增加 nums[2] 数组变为 [1,1,2]
//2) 增加 nums[1] 数组变为 [1,2,2]
//3) 增加 nums[2] 数组变为 [1,2,3]
//
//
// 示例 2
//
// 输入nums = [1,5,2,4,1]
//输出14
//
//
// 示例 3
//
// 输入nums = [8]
//输出0
//
//
//
//
// 提示
//
//
// 1 <= nums.length <= 5000
// 1 <= nums[i] <= 104
//
// Related Topics 贪心算法 数组
// 👍 7 👎 0
package leetcode.editor.cn;
//1827:最少操作使数组递增
public class MinimumOperationsToMakeTheArrayIncreasing{
public static void main(String[] args) {
//测试代码
Solution solution = new MinimumOperationsToMakeTheArrayIncreasing().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int minOperations(int[] nums) {
int left = nums[0] - 1;
int sum = 0;
for (int num : nums) {
if (num <= left) {
sum += left - num + 1;
left++;
}else{
left = num;
}
}
return sum;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,43 @@
<p>给你一个整数数组 <code>nums</code> <strong>下标从 0 开始</strong>)。每一次操作中,你可以选择数组中一个元素,并将它增加 <code>1</code> 。</p>
<ul>
<li>比方说,如果 <code>nums = [1,2,3]</code> ,你可以选择增加 <code>nums[1]</code> 得到 <code>nums = [1,<b>3</b>,3]</code> 。</li>
</ul>
<p>请你返回使 <code>nums</code> <strong>严格递增</strong> 的 <strong>最少</strong> 操作次数。</p>
<p>我们称数组 <code>nums</code> 是 <strong>严格递增的</strong> ,当它满足对于所有的 <code>0 &lt;= i &lt; nums.length - 1</code> 都有 <code>nums[i] &lt; nums[i+1]</code> 。一个长度为 <code>1</code> 的数组是严格递增的一种特殊情况。</p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre><b>输入:</b>nums = [1,1,1]
<b>输出:</b>3
<b>解释:</b>你可以进行如下操作:
1) 增加 nums[2] ,数组变为 [1,1,<strong>2</strong>] 。
2) 增加 nums[1] ,数组变为 [1,<strong>2</strong>,2] 。
3) 增加 nums[2] ,数组变为 [1,2,<strong>3</strong>] 。
</pre>
<p><strong>示例 2</strong></p>
<pre><b>输入:</b>nums = [1,5,2,4,1]
<b>输出:</b>14
</pre>
<p><strong>示例 3</strong></p>
<pre><b>输入:</b>nums = [8]
<b>输出:</b>0
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= nums.length &lt;= 5000</code></li>
<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
</ul>
<div><div>Related Topics</div><div><li>贪心算法</li><li>数组</li></div></div>\n<div><li>👍 7</li><li>👎 0</li></div>