1055. 股票买卖 II - AcWing题库
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int[] a = new int[100010];
int n = sc.nextInt();
for(int i = 0; i < n; i ++){
a[i] = sc.nextInt();
}
int res = 0;
for(int i = 0; i < n - 1; i ++){
res += Math.max(0, a[i + 1] - a[i]);
}
System.out.print(res);
}
}
104. 货仓选址 - AcWing题库
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[100010];
for(int i = 0; i < n; i ++){
a[i] = sc.nextInt();
}
Arrays.sort(a, 0, n);
int res = 0;
for(int i = 0; i < n; i ++){
res += Math.abs(a[i] - a[n / 2]);
}
System.out.print(res);
}
}
122. 糖果传递 - AcWing题库
本质上是一个货仓选址问题
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[] a = new long[1000010];
long[] c = new long[1000010];
long sum = 0;
for(int i = 0; i < n; i ++){
a[i] = sc.nextInt();
sum += a[i];
}
long avg = sum / n;
c[n - 1] = avg - a[n - 1];
for(int i = n - 2; i > 0; i --){
c[i] = c[i + 1] + avg - a[i];
}
Arrays.sort(c, 0, n);
long res = 0;
for(int i = 0; i < n; i ++){
res += Math.abs(c[i] - c[n / 2]);
}
System.out.print(res);
}
}
112. 雷达设备 - AcWing题库
1235. 付账问题 - AcWing题库
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double S = sc.nextDouble();
int[] a = new int[n];
for(int i = 0; i < n; i ++){
a[i] = sc.nextInt();
}
Arrays.sort(a, 0, n);
double avg = S / n;
double res = 0;
for(int i = 0; i < n; i ++){
double cur = S / (n - i);
if(a[i] < cur) cur = a[i];
res += (cur - avg) * (cur - avg);
S -= cur;
}
System.out.printf("%.4f", Math.sqrt(res / n));
}
}
1239. 乘积最大 - AcWing题库
import java.util.*;
public class Main{
static int N = 100010;
static long mod = 1000000009;
static int[] a = new int[N];
static int n, k;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
k = sc.nextInt();
for(int i = 0; i < n; i ++){
a[i] = sc.nextInt();
}
Arrays.sort(a, 0, n);
int l = 0, r = n - 1;
long res = 1;
int sign = 1;
if(k % 2 == 1){
res = a[r --];
k --;
if(res < 0) sign = -1;
}
while(k > 0){
long x = (long)a[l] * a[l + 1];
long y = (long)a[r] * a[r - 1];
if(x * sign > y * sign){
res = x % mod * res % mod;
l += 2;
}else{
res = y % mod * res % mod;
r -= 2;
}
k -= 2;
}
System.out.print(res);
}
}