【LeetCode】5638.喫蘋果的最大數目

題目鏈接

5638. 喫蘋果的最大數目

題目描述

解題思路

貪心+優先隊列

就和平時喫零食一樣,優先把快過期的零食喫完,同理,在本題中優先喫那些即將過期的蘋果.

如何才能知道現在那些蘋果最快就要過期,這些快要過期的蘋果又還剩餘幾個呢??

利用優先隊列,隊列中存儲的就是一個二維數組,[蘋果數目,蘋果過期時間].

AC代碼

class Solution {
    public int eatenApples(int[] apples, int[] days) {
        Queue<int[]> q = new PriorityQueue<>(new Comparator<int[]>(){
            public int compare(int[] i1,int[] i2){
                return i1[1] - i2[1];
            }
        });
        int ans = 0;
        for(int i = 0; i < apples.length; i++){
            //1.清理蘋果剩餘爲0以及過期蘋果
            while(!q.isEmpty()){
                int[] temp = q.peek();
                if(temp[0] <= 0 || temp[1] < i){
                    q.poll();
                }else break;
            }
            //2.添加當天新長出的蘋果,如果當天蘋果數爲0,則跳過
            if(apples[i] > 0){
                int pair[] = new int[2];
                pair[0] = apples[i];
                pair[1] = i + days[i] - 1;
                q.offer(pair);
            }
            //3.優先喫最早過期的.
            int temp[] = q.peek();
            if(temp != null){
                temp[0]--;
                ans++;  
            }
        }
        //優先隊列中還存在着元素,接着喫蘋果.value代表當前天數
        int value = apples.length;
        while(!q.isEmpty()){
            int temp[] = q.peek();
            if(temp[0] == 0 || temp[1] < value){
                q.poll();
            }else{
                temp[0]--;
                ans++;
                value++;
            } 
        }
        return ans;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章