0
点赞
收藏
分享

微信扫一扫

洛谷——纪念品分组

醉东枫 2022-02-08 阅读 58
贪心排序

题目链接:纪念品分组

java代码:

import java.util.Arrays;
import java.util.Scanner;

public class Main {
	
	public static void main(String[] args) {
		
		int w,n,count = 0;
		Scanner in = new Scanner(System.in);
		w = in.nextInt();
		n = in.nextInt();
		
//		初始化数组并按升序排序
		int arr[] = new int[n];
		for(int i=0;i<n;++i)
			arr[i] = in.nextInt();
		Arrays.sort(arr);
		
//		设置左右指针,分别指向价格最小和价格最大的纪念品
//		要求分组最少,那就是尽量都是两两一组,所以价格小的和价格大的纪念品组起来,更有可能不超上限,两两一组的才会更多
		int left = 0, right = n-1;
		while(left<right) {
			if(arr[left]+arr[right]<=w) {
				count++;
				right--;
				left++;
			}
			else right--;
		}
		
		System.out.println(n-count);
	}
}
举报

相关推荐

0 条评论