题解 | #数的选择#前缀和的思想
数的选择
https://www.nowcoder.com/practice/12f72e06fc424e4d9c685cd89f2bed36
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
int n=in.nextInt();
int[]nums=new int[n];
for (int i = 0; i < n; i++) {
nums[i]=in.nextInt();
}
Arrays.sort(nums);
long[]small=new long[n];
small[0]=nums[0];
for (int i = 1; i < n; i++) {
small[i]=small[i-1]+nums[i];
}
long[]big=new long[n];
long[]copy=new long[n];
for (int i = 0; i < n; i++) {
copy[i]=nums[nums.length-1-i];
}
big[0]=copy[0];
for (int i =1; i <n; i++) {
big[i]=big[i-1]+copy[i];
}
int left=1,right=0;
while(left<nums.length) {
if (big[right] > small[left]) {
System.out.println(right+1);
return;
}
right++;
if(right<=left){
left++;
}
}
if(left==nums.length){
System.out.println(-1);
}
}
}
查看8道真题和解析
