原题链接:4262. 空调 - AcWing题库https://www.acwing.com/problem/content/4265/
解题代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/*
* 输入格式:
* 数量
* 希望温度 t
* 实际温度 p
* */
/*
* 利用了导数的思想
* 差分数组
* 从实际温度到希望温度需要变化的就是从一个全0数组变到这个希望温度的数组逐个减去实际温度的数组组成的数组
* ==> p => t 就等于 全0数组 => [p-t]
* 假设 [p-t] = psub这个数组
* 求处psub 这个数组的差分数组,因为,在p 和 t数组中,由 实际温度变化到希望温度的过程是一个区间变化的过程
* 由此,我们应该想到使用 差分数组 这样 就可以把区间的变化转换成 数轴上两个点的变化
*
*
* */
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
int[] p = new int[n + 10]; // 希望温度
int[] t = new int[n + 10]; // 实际温度
String[] pstr = reader.readLine().split(" ");
for (int i = 1; i <= n; i++) {
p[i] = Integer.parseInt(pstr[i - 1]);
}
String[] tstr = reader.readLine().split(" ");
for (int i = 1; i <= n; i++) {
t[i] = Integer.parseInt(tstr[i - 1]);
}
for (int i = 1; i <= n; i++) {
p[i] -= t[i];
}
// 读取数据完成
int[] psub = new int[n + 10];
// 求出 实际温度和希望温度的差分数组
for (int i = 1; i <= n + 1; i++) {
psub[i] = p[i] - p[i - 1];
}
int res = 0;
for (int i = 1; i <= n + 1; i++) {
if (psub[i] > 0) {
res += psub[i];
}
}
System.out.println(res);
}
}