Implement solution for Best Time to Buy and Sell Stock III#7
Merged
Subhosjx merged 1 commit intoSubhosjx:mainfrom Oct 28, 2025
Merged
Implement solution for Best Time to Buy and Sell Stock III#7Subhosjx merged 1 commit intoSubhosjx:mainfrom
Subhosjx merged 1 commit intoSubhosjx:mainfrom
Conversation
🎉 Congrats on getting your PR merged in, @SjxSubham! 🙌🏼Thanks for your contribution every effort helps improve the project. Looking forward to seeing more from you! 🥳✨ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Intuition
Each course may depend on others, forming a dependency graph. We start with courses having no prerequisites and “complete” them, freeing dependent courses. Repeating this, we process all courses whose prerequisites are satisfied. If all courses are completed, finishing is possible; otherwise, a cycle exists, making it impossible.
Approach
We first represent the course prerequisites as a directed graph, where each course is a node and an edge from course b to course a indicates that b must be completed before a. We then compute the in-degree for every course, which counts how many prerequisites each course has. Courses with zero in-degree can be taken immediately, so we add them to a queue. We repeatedly process courses from the queue, and for each course taken, we reduce the in-degree of its dependent courses. If a dependent course’s in-degree becomes zero, it means all its prerequisites are completed, and we add it to the queue. Finally, if we manage to process all courses, it means there are no cycles and it is possible to finish all courses; otherwise, the presence of a cycle prevents completion.