贝克第四题
求大佬帮看看有什么问题,82%,
思路就是,用4个前缀数组,做一个递增的,一个递减的序列,然后更新min值找最小
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] nums = new int[n];
for(int i = 0;i<n;i++)
nums[i] = input.nextInt();
System.out.println(minAdd(nums));
}
public static int minAdd(int[] nums) {
int n = nums.length;
int[] i_mods = new int[n];
int[] d_mods = new int[n];
int[] i_maxs = new int[n];
int[] d_maxs = new int[n];
for (int i = 0; i < n; i++) {
if (i == 0) {
i_mods[i] = 0;
i_maxs[i] = nums[i];
continue;
}
int max = Math.max(nums[i], i_maxs[i - 1] + 1);
i_mods[i] = max - nums[i] + i_mods[i - 1];
i_maxs[i] = max;
}
for (int i = n - 1; i >= 0; i--) {
if (i == n - 1) {
d_mods[i] = 0;
d_maxs[i] = nums[i];
continue;
}
int max = Math.max(nums[i], d_maxs[i + 1] + 1);
d_mods[i] = max - nums[i] + d_mods[i + 1];
d_maxs[i] = max;
}
int min = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int mod = i_mods[i] + d_mods[i] - (Math.min(i_maxs[i], d_maxs[i]) - nums[i]);
min = Math.min(mod, min);
}
min = Math.min(i_mods[n-1],min);
min = Math.min(d_mods[0],min);
return min;
}
}
#笔试题目##春招#