leetcode刷题笔记5638题 吃苹果的最大数目

leetcode刷题笔记5638题 吃苹果的最大数目

地址:5638. 吃苹果的最大数目

问题描述:

import scala.collection.mutable.PriorityQueue
object Solution {
    def eatenApples(apples: Array[Int], days: Array[Int]): Int = {
        val heap = PriorityQueue.empty[(Int, Int)](Ordering.by(n => n._1)).reverse
        var res = 0
        var n = apples.length
        var i = 0

        while (i < n || heap.length > 0){
        //while (i < 10){
            if (i < n && apples(i) > 0) {
                heap.enqueue(((i + days(i) -1), apples(i)))
            }
            while (heap.length > 0 && heap.head._1 < i) {
                var  temp = heap.dequeue
            }
            if (heap.length > 0) {
                var x = heap.dequeue
                res += 1
                if (x._2-1 > 0) {
                    heap.enqueue((x._1, x._2-1))
                }
            }
            i += 1 
        }
        return res
    }
}
import (
    "container/heap"
    "fmt"
)

type Item struct {
    day int
    apple int
}

type PriortyQueue []*Item

func (pq PriortyQueue) Len() int {return len(pq)}
func (pq PriortyQueue) Less(i, j int) bool {
    return pq[i].day > pq[j].day
}
func (pq PriortyQueue) Swap(i, j int) {
    pq[i], pq[j] = pq[j], pq[i]
}

func (pq *PriortyQueue) Push(x interface{}) {
    item := x.(*Item)
    *pq = append(*pq, item)
}

func (pq *PriortyQueue) Pop() interface{} {
    old := *pq
    n := len(old)
    item := old[n-1]
    old[n-1] = nil
    *pq = old[0:n-1]
    return item
}

func eatenApples(apples []int, days []int) int {
    pq := make(PriortyQueue, 0)
    n := len(apples)
    res := 0
    for i := 0; i <= 40000; i++ {

        if i < n && apples[i] > 0 {
            heap.Push(&pq, &Item{day: i+days[i]-1, apple: apples[i]})
        }
        for pq.Len() > 0 && pq[pq.Len()-1].day < i {
            _ = pq.Pop()    
        }
        if pq.Len() == 0 {continue}
        x := pq.Pop().(*Item)
        x.apple -= 1
        res += 1
        if x.apple > 0 {heap.Push(&pq, x)}
    }
    return res
}
原文地址:https://www.cnblogs.com/ganshuoos/p/14199251.html