一个序列,可以随时抛,买股票,怎么说呢。
就是一个类似逆序对,累计差值的双指针。
打个比方1, 2, 3, 4, 6, 7, 8, 9,两个算法
1. 2 - 1 + 3 - 2 + 4 - 3 + …
2. 9 - 1
其实答案是一样的,所以只需要双指针,后面的指针找到最后一个大于后一项的数,累加就可以了。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static int N = 100010, n;
static int a[] = new int[N];
static long res = 0;
public static void main(String[] args) throws Exception {
n = Integer.parseInt(br.readLine());
String s[] = br.readLine().split(" ");
for (int i = 0; i < n; i++) a[i] = Integer.parseInt(s[i]);
if (n == 1) { //特判一下1的情况
System.out.println(0);
System.exit(0);
}
int i = 0, j = 1;
while (i < n && j < n) {
while (i < n && j < n && a[i] < a[j]) {
res += a[j] - a[i];
i = j;
j++;
}
i = j;
j++;
}
pw.print(res);
pw.flush();
pw.close();
br.close();
}
}