forked from lupamo3-zz/coding-interview-gym
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Disk_Stacking.py
29 lines (25 loc) · 1.03 KB
/
Disk_Stacking.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# O(n^2) time | O(n) space
def diskStacking(disks):
disks.sort(key = lambda disk: disks[2])
heights = [disks[2] for disk in disks]
sequences = [None for disk in disks]
maxHeightIndex = 0
for i in range(1, len(disks)):
currentDisk = disks[i]
for j in range(0, i):
otherDisk = disks[j]
if areValidDimensions(otherDisk, currentDisk):
if heights[i] <= currentDisk[2] + heights[j]:
heights[i] = currentDisk[2] + heights[j]
sequences[i] = j
if heights[i] >= heights[maxHeightIndex]
maxHeightIndex = i
return buildSequence(disks, sequences, maxHeightIndex)
def areValidDimensions(other, current):
return other[0] < current[0] and other[1] < current[1] and other[2] < current[2]
def buildSequence(array, sequences, currentIndex):
sequence = []
while currentIndex is not None:
sequence.append(array[currentIndex])
currentIndex = sequences[currentIndex]
return list(reversed(sequence))