Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 502 · Two Heaps

IPO

LeetCode 502 · ಕಠಿಣ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Sort by capital; max-heap of affordable profits.

ಕಠಿಣArrayGreedySortingHeap (Priority Queue)
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು IPO (LeetCode 502) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Two Heaps ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಕಠಿಣ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

At any moment you can afford some projects; pick the most profitable affordable one, which raises your capital and may unlock more. Sort projects by required capital, and move newly affordable ones into a max-heap of profits each round.

Approach

  1. 1

    Pair (capital, profit) and sort.

  2. 2

    Each round, push every newly affordable project's profit.

  3. 3

    Take the largest profit; stop early if nothing is affordable.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Sort + max-heapPythonO(n log n) time
class Solution:
    def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:
        #we need to take minimal capital items first, whichever items is not available now might be available in the future
        #maximize profit
        projects = list(zip(capital,profits))
        projects.sort()
        max_heap = []
        j=0
        for i in range(k):
            while j<len(projects) and projects[j][0]<=w:
                 heapq.heappush(max_heap,-projects[j][1])
                 j+=1
            if not max_heap:
                break
            w+= -heapq.heappop(max_heap)
        return w
        
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

IPO — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

IPO ಹಿಂದಿನ intuition ಏನು?

At any moment you can afford some projects; pick the most profitable affordable one, which raises your capital and may unlock more. Sort projects by required capital, and move newly affordable ones into a max-heap of profits each round.

IPO (LeetCode 502) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Pair (capital, profit) and sort. 2. Each round, push every newly affordable project's profit. 3. Take the largest profit; stop early if nothing is affordable.

IPO ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n log n + k log n). Space: O(n). (Accepted approach: Sort + max-heap.)

IPO ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Unaffordable projects aren't discarded — they may become affordable later.