leetcode 2279. Maximum Bags With Full Capacity of Rocks(装满石头的最大袋子数)


简易的背包问题,capacity数组是每个背包的容量,rocks数组表示每个背包里面已经有多少石头,现有additionalRocks个石头可以继续往背包里面加,问最多能填满多少个背包。

思路:

greedy

只需要先计算每个背包还能放多少个石头,然后用additionalRocks个石头从需求量小的开始加,这样就能填满最多的背包。

    public int maximumBags(int[] capacity, int[] rocks, int additionalRocks) {
        int n = capacity.length;
        int[] diff = new int[n];
        int res = 0;
        
        for(int i = 0; i < n; i++) {
            diff[i] = capacity[i] - rocks[i];
        }

        Arrays.sort(diff);

        for(int i = 0; i < n; i++) {
            additionalRocks -= diff[i];
            if(additionalRocks < 0) break;
            res ++;
        }

        return res;
    }

你可能感兴趣的:(leetcode,leetcode,算法,数据结构)