forked from mission-peace/interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbitonicsequence.py
More file actions
48 lines (35 loc) · 1.35 KB
/
bitonicsequence.py
File metadata and controls
48 lines (35 loc) · 1.35 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
Problem Statement
=================
Find the length of the longest Bitonic Sequence in a given sequence of numbers. A Bitonic sequence is a sequence of
numbers which are increasing and then decreasing.
Video
-----
* https://youtu.be/TWHytKnOPaQ
Analysis
--------
* Runtime O(n)
Reference
---------
* http://www.geeksforgeeks.org/dynamic-programming-set-15-longest-bitonic-subsequence/
"""
def longest_bitonic(sequence):
length_of_input = len(sequence)
increasing_sequence = [1] * length_of_input
decreasing_sequence = [1] * length_of_input
for i in range(1, length_of_input):
for j in range(0, i):
if sequence[i] > sequence[j]:
increasing_sequence[i] = max(increasing_sequence[i], increasing_sequence[j] + 1)
for i in range(length_of_input - 2, -1, -1):
for j in range(length_of_input - 1, i, -1):
if sequence[i] > sequence[j]:
decreasing_sequence[i] = max(decreasing_sequence[i], decreasing_sequence[j] + 1)
max_value = 0
for i in range(len(sequence)):
bitonic_sequence_length = increasing_sequence[i] + decreasing_sequence[i] - 1
max_value = max(max_value, bitonic_sequence_length)
return max_value
if __name__ == '__main__':
max_value = longest_bitonic([1, 4, 3, 7, 2, 1, 8, 11, 13, 0])
assert 7 == max_value # 1, 4, 7, 8, 11, 13, 0