public long IncreasingArray (int[] array) { // write code here long res = 0; for (int i = 1; i < array.length; i++){ if (array[i] <= array[i-1]) { res += array[i-1]-array[i]+1; } } return res; }
class Solution: def IncreasingArray(self , array ): res = 0 for i in range(1,len(array)): diff = array[i]-array[i-1] if diff < 0: res += 1 - diff return res答案是看了各位网友的讨论之后才写的,几乎是抄袭,比较简洁。也可以直接用一行代码解决,如下:
class Solution: def IncreasingArray(self , array ): return sum([1-array[i]+array[i-1] for i in range(1,len(array)) if array[i]-array[i-1]<0])思路:
function IncreasingArray(arr) { let cnt = BigInt(0) arr.map(e=> BigInt(e)) for (let i = 0; i < arr.length-1; i++) { if(BigInt(arr[i])>BigInt(arr[i+1])) cnt += (BigInt(arr[i])-BigInt(arr[i+1]) + 1n) } return cnt } module.exports = { IncreasingArray : IncreasingArray };
/** * * @param array int整型一维数组 array * @return long长整型 */ function IncreasingArray( array ) { // write code here var count=0;//计数 var p;//暂存 for(let i=1;i<array.length;i++){ if(array[i]<=array[i-1]){//比直接左边数值小,就要计数 p=array[i-1]+1-array[i];//严格递增,+1:把相等的情况跳过去 count+=p; } } return count; } module.exports = { IncreasingArray : IncreasingArray };
import java.util.*; public class Solution { /** * * @param array int整型一维数组 array * @return long长整型 */ public long IncreasingArray (int[] array) { long result = 0; for(int i=0;i<array.length-1;i++){ if(array[i+1] <= array[i]){ int sub = array[i] - array[i+1] + 1; result += sub; } } return result; } }
#define ll long long class Solution { public: /** * * @param array int整型vector array * @return long长整型 */ long long IncreasingArray(vector<int>& a) { // write code here int n = a.size(); ll res = 0; for(int i=1;i<n;i++){ res+=max(a[i-1]+1-a[i],0); } return res; } };
每次选择一个区间,其实只能改变区间端点处的单调性,区间内部的单调性无法改变, 并且右端点还可能由递增变为两数相等 所以,每次让一个数增加,其实就是最优化的方案 long long IncreasingArray(vector<int>& array) { long long res = 0; for(int i=1;i<array.size();i++){ int difference = array[i] - array[i-1]; if(difference <= 0){ res += 1 - difference; } } return res; }