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 Number of Weeks for Work INPUT milestones array: 1 P0 2 P1 3 P2 Visual: Milestone blocks P0: P1: P2: Total milestones: 1 + 2 + 3 = 6 ALGORITHM STEPS 1 Calculate Sum total = sum(milestones) total = 6 2 Find Maximum maxM = max(milestones) maxM = 3 3 Calculate Rest rest = total - maxM rest = 6 - 3 = 3 4 Apply Formula if maxM > rest + 1: return 2*rest + 1 else: return total Check: 3 > 3 + 1 ? 3 > 4 ? NO Return total = 6 FINAL RESULT Maximum weeks of work: 6 Valid Schedule Example: W1 P2 W2 P1 W3 P2 W4 P0 W5 P2 W6 P1 OK - All Complete! All 6 milestones done No consecutive same project violations Key Insight: The greedy solution works because we can always interleave milestones optimally. If the largest project has more milestones than all others combined + 1, we're limited to (2 * rest + 1) weeks. Otherwise, we can complete all milestones. Formula: max(2*rest+1, total) where rest = total - maxM TutorialsPoint - Maximum Number of Weeks for Which You Can Work | Mathematical Greedy Solution
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