书籍复印
https://www.lintcode.com/problem/437
输入: pages = [3, 2, 4], k = 2输出: 5解释: 第一个人复印前两本书, 耗时 5 分钟. 第二个人复印第三本书, 耗时 4 分钟.输入: pages = [3, 2, 4], k = 3输出: 4解释: 三个人各复印一本书.Last updated
https://www.lintcode.com/problem/437
输入: pages = [3, 2, 4], k = 2输出: 5解释: 第一个人复印前两本书, 耗时 5 分钟. 第二个人复印第三本书, 耗时 4 分钟.输入: pages = [3, 2, 4], k = 3输出: 4解释: 三个人各复印一本书.Last updated
from typing import (
List,
)
class Solution:
"""
@param pages: an array of integers
@param k: An integer
@return: an integer
"""
def copy_books(self, pages: List[int], k: int) -> int:
# write your code here
if not pages:
return 0
max_pages = max(pages)
sum_pages = sum(pages)
s, e = max_pages, sum_pages
while s + 1 < e:
mid = (s+e)//2
if(self.can_copy(pages, k, mid)):
e = mid
else:
s = mid
if(self.can_copy(pages, k, s)):
return s
return e
def can_copy(self, pages: List[int], k: int, capacity: int) -> bool:
total, worker = 0, 1
for p in pages:
if total + p > capacity: #打印任务 > 可负荷量,需要加人
worker += 1
total = 0
total += p #不在else里 total无论如何每次都要更新
return worker <= k