题解
第一题暴力,第二题不用三分直接暴力,待补充。
代码
第一题
import java.util.*;
public class csp202109_01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int len = sc.nextInt();
int minSum = 0, maxSum = 0, tempMax = -1;
for (int i = 0; i < len; i++){
int num = sc.nextInt();
maxSum += num;
if(num > tempMax) minSum += num;
// tempMax = Math.max(num, tempMax);
tempMax = num;
}
System.out.println(maxSum);
System.out.println(minSum);
}
}
第二题
import java.util.*;
public class csp202109_02 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int len = sc.nextInt();
int[] nums = new int[len + 2];
nums[0] = 0;
nums[len + 1] = 0;
Map<Integer, LinkedList<Integer>> map = new HashMap<>(); // unsorted keys
// [1, len]
for (int i = 1; i < len + 1; i++) {
nums[i] = sc.nextInt();
if (nums[i] != 0) {
LinkedList<Integer> temp;
if (map.containsKey(nums[i])) {
temp = map.get(nums[i]);
} else {
temp = new LinkedList<>();
}
temp.add(i);
map.put(nums[i], temp);
}
}
// sorted keys
LinkedList<Integer> keys = new LinkedList<>(map.keySet());
Collections.sort(keys);
// scan
int countInterval = getInterval(nums);
int max = countInterval;
for(int key : keys){
LinkedList<Integer> list = map.get(key);
for (int index : list) {
// set zero
nums[index] = 0;
// change the current countInterval
if ((nums[index - 1] != 0) && (nums[index + 1] != 0)) {
countInterval++;
} else if (nums[index - 1] == 0 && nums[index + 1] == 0) {
countInterval--;
} // else{ 0a1 1a0 does not matter}
}
max = Math.max(countInterval, max);
}
System.out.println(max);
}
private static int getInterval(int[] nums) {
int count = 0;
int lenNums = nums.length;
for (int i = 0; i < lenNums; i++) {
if (nums[i] == 0) {
continue;
} else {
count++;
}
while (i < lenNums && nums[i] != 0) i++;
}
return count;
}
}