Skip to content

Instantly share code, notes, and snippets.

@xeonqq
Last active August 29, 2015 14:26
Show Gist options
  • Save xeonqq/dcef8c74bc474f55e756 to your computer and use it in GitHub Desktop.
Save xeonqq/dcef8c74bc474f55e756 to your computer and use it in GitHub Desktop.
Divide array A into K blocks and minimize the largest sum of any block.
def blockPossible(A, bound, K):
s = A[0]
blocks = 1;
for a in A[1:]:
s += a
if s>bound:
blocks+=1
s=a
if blocks > K:
return False
return True
def solution(K, M, A):
# write your code in Python 2.7
UpperBound = sum(A)
LowerBound = max(A)
if K <= 1:
return UpperBound
if K > len(A):
return LowerBound
result = UpperBound
while LowerBound <= UpperBound:
midBound = (LowerBound + UpperBound)/2
if blockPossible(A, midBound, K):
UpperBound = midBound-1
result = midBound
else:
LowerBound = midBound+1
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment