LeetCode in Kotlin

1953. Maximum Number of Weeks for Which You Can Work

Medium

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:

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.

Example 1:

Input: milestones = [1,2,3]

Output: 6

Explanation: One possible scenario is:

The total number of weeks is 6.

Example 2:

Input: milestones = [5,2,1]

Output: 7

Explanation: One possible scenario is:

The total number of weeks is 7. Note that you cannot work on the last milestone of project 0 on 8th week because it would violate the rules. Thus, one milestone in project 0 will remain unfinished.

Constraints:

Solution

class Solution {
    fun numberOfWeeks(milestones: IntArray): Long {
        var sum: Long = 0
        var max: Long = 0
        for (m in milestones) {
            sum += m.toLong()
            max = Math.max(max, m.toLong())
        }
        return if (sum - max + 1 >= max) sum else 1 + 2 * (sum - max)
    }
}