代码:
C++:
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define LL long long
const LL maxnum = 3e5 + 5;
LL a[maxnum];
LL d[maxnum]; //差分数组
int main()
{
int n;
cin >> n;
for(int i = 1;i <= n;i ++)
{
cin >> a[i];
}
for(int i = 1;i <= n;i ++)
{
d[i] = a[i] - a[i - 1];
}
LL s = 0,s2 = 0;
for(int i = 2;i <= n;i ++)
{
if(d[i] > 0) s += d[i];//差分数组整数和
else{
s2 -= d[i]; //差分数组负数和
}
}
//正数大则最小次就是正数,负数大则最小次就是负数
//
cout << max(s,s2) <<endl <<abs(s - s2) + 1;
return 0;
}
Java:
package lanqiao;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n + 1];
int[] d = new int[n + 1]; //差分
long s = 0,s2 = 0;
for(int i = 1;i <= n;i ++)
{
a[i] = sc.nextInt();
}
for(int i = 1;i <= n;i ++)
{
d[i] = a[i] - a[i - 1];
}
for(int i = 2;i<= n;i ++)
{
if(d[i] > 0) s += d[i];
else s2 -= d[i];
}
System.out.println(Math.max(s,s2));
System.out.println(Math.abs(s - s2) + 1);
}
}