Google codejam 2018 第一题 JAVA 解法

#1题目是:

Yogurt can be a nutritious part of an appetizer, main course, or dessert, but it must be consumed before it expires, and it might expire quickly! Moreover, different cups of yogurt might expire on different days.Lucy loves yogurt, and she has just bought N cups of yogurt, but she is worried that she might not be able to consume all of them before they expire. The i-th cup of yogurt will expire Ai days from today, and a cup of yogurt cannot be consumed on the day it expires, or on any day after that.As much as Lucy loves yogurt, she can still only consume at most K cups of yogurt each day. What is the largest number of cups of yogurt that she can consume, starting from today?

Input

The first line of the input gives the number of test cases, T. T test cases follow. Each test case starts with one line containing two integers N and K, as described above. Then, there is one more line with N integers Ai, as described above.

Output

For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the maximum number of cups of yogurt that Lucy can consume, as described above.

#2分析

看题看了老久,其实意思就是,如果你同一天买了N个酸奶,第i个第Ai天过期,你一天最多吃K个,请问最多吃多少个。

思路就是先排序然后贪心算法

#3 代码

package com.study.Algorithm;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MaxNums {
    private static class Yogurt implements Comparable {
        public int expiredTime;

        public Yogurt(int expiredTime) {
            this.expiredTime = expiredTime;
        }

        @Override
        public String toString() {
            return "Yogurt{" +
                    "expiredTime=" + expiredTime +
                    '}';
        }

        @Override
        public int compareTo(Yogurt o) {
            if (this.expiredTime < o.expiredTime) {
                return -1;
            } else if (this.expiredTime > o.expiredTime) {
                return 1;
            } else
                return 0;
        }

    }

    public static int getMaxNums(List yogurts, int k) {
        Collections.sort(yogurts);
        System.out.println(yogurts);
        int nowTime = 0;
        List BestWays = new ArrayList<>();
        boolean j = false;
        do {
            int nums = 0;
            for (int i = 0; i < yogurts.size(); i++) {
                Yogurt yog = yogurts.get(i);
                if (yog.expiredTime > nowTime && nums < k) {
                    BestWays.add(yog);
                    nums++;
                    yogurts.set(i, new Yogurt(0));
                }

            }
            nowTime++;
            if (yogurts.size() != 0) {
                if (yogurts.get(yogurts.size() - 1).expiredTime >= nowTime) {
                    j = true;
                } else j = false;
            } else j = false;
        } while (j);

        System.out.println("最佳顺序:" + BestWays);
        return BestWays.size();
    }

}

 

 

你可能感兴趣的:(算法题目相关JAVA)