Approaches
💡
Intuition
Time O(n²)Space O(1)
The brute force approach involves simulating each week and selecting milestones from projects while adhering to the constraints. This method is straightforward but inefficient as it checks all possible combinations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a week counter to zero.
- 2Step 2: While there are milestones left in any project, select the project with the highest remaining milestones that can be worked on without violating the consecutive week rule.
- 3Step 3: Increment the week counter and update the milestones for the selected project. Repeat until no valid selections are possible.
solution.py18 lines
1# Full working Python code
2from collections import Counter
3
4def maxWeeks(milestones):
5 weeks = 0
6 while True:
7 milestones.sort(reverse=True)
8 if milestones[0] == 0:
9 break
10 for i in range(len(milestones)):
11 if milestones[i] > 0:
12 weeks += 1
13 milestones[i] -= 1
14 if i + 1 < len(milestones) and milestones[i + 1] > 0:
15 milestones[i + 1] -= 1
16 break
17 return weeks
18ℹ
Complexity note: The time complexity is O(n²) because we sort the milestones array in each iteration, which takes O(n log n), and we may do this for each milestone, resulting in a quadratic relationship.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.