Maximum Number of Weeks for Which You Can Work - Problem

There are n projects numbered from 0 to n - 1. You are given an integer array milestones where each milestones[i] denotes the number of milestones the ith project has.

You can work on the projects following these two rules:

  • Every week, you will finish exactly one milestone of one project. You must work every week.
  • You cannot work on two milestones from the same project for two consecutive weeks.

Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working. Note that you may not be able to finish every project's milestones due to these constraints.

Return the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above.

Input & Output

Example 1 — Basic Case
$ Input: milestones = [1,2,3]
Output: 6
💡 Note: We can work on all milestones: Week 1-Project 2, Week 2-Project 1, Week 3-Project 2, Week 4-Project 0, Week 5-Project 2, Week 6-Project 1. Total: 6 weeks.
Example 2 — Constraint Limiting
$ Input: milestones = [5,2,1]
Output: 7
💡 Note: Project 0 has 5 milestones, others have 3 total. We can work: P0-P1-P0-P2-P0-P1-P0, then stop (can't work on P0 again). Total: 7 weeks.
Example 3 — Equal Projects
$ Input: milestones = [5,5,5]
Output: 15
💡 Note: All projects equal, can perfectly interleave: P0-P1-P2-P0-P1-P2... until all done. Total: 15 weeks.

Constraints

  • n == milestones.length
  • 1 ≤ n ≤ 105
  • 1 ≤ milestones[i] ≤ 109

Visualization

Tap to expand
Maximum Working Weeks Problem123Project 0Project 1Project 2Optimal Schedule (6 weeks):212021Week 1Week 2Week 3Week 4Week 5Week 6✓ No consecutive weeks on same project✓ All milestones completedAnswer: 6 weeks
Understanding the Visualization
1
Input
Array of project milestones: [1,2,3]
2
Constraint
Cannot work same project two consecutive weeks
3
Schedule
Find optimal interleaving pattern
4
Output
Maximum weeks possible: 6
Key Takeaway
🎯 Key Insight: Maximum weeks depends on whether the largest project can be interleaved with all others
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen