Maximum number of apples that can be eaten by a person | C ++ program of the above approach ; Function to find the maximum number of apples a person can eat such that the person eat at most one apple in a day . ; Stores count of apples and number of days those apples are edible ; Store count of apples and number of days those apples are edible ; Stores indices of the array ; Stores count of days ; Stores maximum count of edible apples ; Traverse both the arrays ; If top element of the apple is not already expired ; Insert count of apples and their expiration date ; Remove outdated apples ; Insert all the apples produces by tree on current day ; Stores top element of pq ; Remove top element of pq ; If count of apples in curr is greater than 0 ; Insert count of apples and their expiration date ; Update total_apples ; Update index ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cntMaxApples ( vector < int > apples , vector < int > days ) { typedef pair < int , int > P ; priority_queue < P , vector < p > , greater < p > > pq ; int i = 0 ; int n = apples . size ( ) ; int total_apples = 0 ; while ( i < n || ! pq . empty ( ) ) { if ( i < n && apples [ i ] != 0 ) { pq . push ( { i + days [ i ] - 1 , apples [ i ] } ) ; } while ( ! pq . empty ( ) && pq . top ( ) . first < i ) { pq . pop ( ) ; } if ( ! pq . empty ( ) ) { auto curr = pq . top ( ) ; pq . pop ( ) ; if ( curr . second > 1 ) { pq . push ( { curr . first , curr . second - 1 } ) ; } ++ total_apples ; } ++ i ; } return total_apples ; } int main ( ) { vector < int > apples = { 1 , 2 , 3 , 5 , 2 } ; vector < int > days = { 3 , 2 , 1 , 4 , 2 } ; cout << cntMaxApples ( apples , days ) ; return 0 ; }