Skip to content

Commit c0f2212

Browse files
committed
upload Lesson 16
1 parent 128cb10 commit c0f2212

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

16-GreedyAlgorithms_cckao.pdf

341 KB
Binary file not shown.

MaxNonoverlappingSegments.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# you can write to stdout for debugging purposes, e.g.
2+
# print("this is a debug message")
3+
4+
def solution(A, B):
5+
# write your code in Python 3.6
6+
7+
# the array is already sorted by B (the right end)
8+
9+
# special cases (zero or only one)
10+
if len(A) == 0:
11+
return 0
12+
elif len(A) == 1:
13+
return 1
14+
15+
# keep 'the current right-end' and 'the current left-end'
16+
current_right_end = B[0]
17+
current_left_end = A[0]
18+
19+
num_non_overlapping = 1
20+
21+
for index in range( len(A) ):
22+
current_left_end = A[index] # moving the left-end
23+
if current_left_end > current_right_end:
24+
num_non_overlapping += 1
25+
current_right_end = B[index] # update the right-end
26+
27+
return num_non_overlapping

TieRopes.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# you can write to stdout for debugging purposes, e.g.
2+
# print("this is a debug message")
3+
4+
import copy
5+
6+
def solution(K, A):
7+
# write your code in Python 3.6
8+
9+
all_rope_list = []
10+
11+
current_length = 0
12+
current_rope_list = []
13+
for item in A:
14+
current_length += item
15+
current_rope_list.append(item)
16+
# print(current_length)
17+
if current_length >= K:
18+
current_length = 0
19+
# all_rope_list.append( current_rope_list )
20+
# very important: need to use 'copy.copy()' for the current list
21+
# print(current_rope_list)
22+
all_rope_list.append( copy.copy(current_rope_list) )
23+
# print(all_rope_list)
24+
current_rope_list.clear()
25+
26+
num_rope = len(all_rope_list)
27+
return num_rope

0 commit comments

Comments
 (0)