Skip to content

Commit f8da7f8

Browse files
committed
upload Lesson 14
1 parent 4f5fbf9 commit f8da7f8

2 files changed

Lines changed: 57 additions & 0 deletions

File tree

14-BinarySearch_cckao.pdf

363 KB
Binary file not shown.

MinMaxDivision.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# you can write to stdout for debugging purposes, e.g.
2+
# print("this is a debug message")
3+
4+
import math
5+
6+
def solution(K, M, A):
7+
# write your code in Python 3.6
8+
9+
# try to find minMaxSum
10+
# we can try 'minMaxSum' by using binary search (fast)
11+
# but, we need to know
12+
# min_possible_sum and max_possible_sum
13+
# so, we can try mid_possible_sum (using binary search)
14+
15+
# 1. find min_possible_sum and max_possible_sum
16+
min_possible_sum = 0
17+
max_possible_sum = 0
18+
for item in A:
19+
min_possible_sum = max(min_possible_sum, item) # at least one element (large)
20+
max_possible_sum += item # at most all elements (sum of all)
21+
#print(min_possible_sum)
22+
#print(max_possible_sum)
23+
24+
# 3. check if mid_possible_sum is 'ok' or not (define the method)
25+
def check_if_mid_sum_possible(K, M, A, mid_sum):
26+
num_block_allowed = K
27+
current_block_sum = 0
28+
for item in A:
29+
current_block_sum += item
30+
if current_block_sum > mid_sum: # need another block
31+
num_block_allowed -= 1
32+
current_block_sum = item # important (the item in next block)
33+
if num_block_allowed ==0:
34+
return False
35+
# all blocks can be smaller than (or equal to) mid_sum
36+
return True
37+
38+
# 2. binary search
39+
result = max_possible_sum
40+
41+
while min_possible_sum <= max_possible_sum:
42+
mid_possible_sum = math.ceil( (min_possible_sum + max_possible_sum) / 2 )
43+
# print(mid_possible_sum)
44+
45+
# try smaller
46+
is_sum_possible = check_if_mid_sum_possible(K, M, A, mid_possible_sum)
47+
# print(is_sum_possible)
48+
if is_sum_possible == True:
49+
result = mid_possible_sum
50+
max_possible_sum = mid_possible_sum - 1
51+
52+
# try bigger
53+
else:
54+
min_possible_sum = mid_possible_sum + 1
55+
56+
return result
57+

0 commit comments

Comments
 (0)