#1953
Medium Algorithms Maximum number of weeks for which you can work
Array Greedy
42.3% acceptance
Feb 25, 2026
695
163
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn number_of_weeks(milestones: Vec<i32>) -> i64 {
let total: i64 = milestones.iter().map(|&x| x as i64).sum();
let max_val = *milestones.iter().max().unwrap() as i64;
let rest = total - max_val;
if max_val > rest + 1 {
2 * rest + 1
} else {
total
}
}
}