-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTime.rb
91 lines (68 loc) · 1.79 KB
/
Time.rb
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def my_min_phase2(arr)
least = arr.first # O1
arr.each_with_index do |ele, i| #On
if least > arr[i] #O1
least = arr[i] #O1
end
end
least # 1 + n * 1 * 1 => n
end
def my_min_phase1(arr)
arr.each_with_index do |el1, i1| # O(n)
min = true # O1
arr.each_with_index do |el2, i2| #On
next if i1 == i2 # O1
min = false if el2 < el1 #O1
end
return el1 if min #O1
end
end
list = [ 0, 3, 5, 4, -5, 10, 1, 90 ]
my_min_phase2(list) # => O(n)
my_min_phase1(list) # => O(n^2)
def largest_contiguous_subsum(arr)
subarrs = []
(0...arr.length).each do |i1|
(i1...arr.length).each do |i2|
subarrs << arr[i1..i2]
end
end
sums = []
subarrs.each do |sub|
sums << sub.sum
end
sums.max
end
def second_largest_contiguous_subsum(arr)
largest = arr.first
current = 0
(0...arr.length).each do |i|
last_i = arr.length - 1
# p arr[i..last_i]
current = arr[i..last_i].sum
largest = current if largest < current
# largest < arr[i]
end
j = arr.length - 1
while j >= 0
current = arr[0..j].sum
p largest
largest = current if largest < current
largest = arr[j] if largest < arr[j]
j -= 1
end
largest
end
list2 = [5, 3, -7]
p second_largest_contiguous_subsum(list2) # => 8
## possible sub-sums
#[5] # => 5
#[5, 3] # => 8 --> we want this one
#[5, 3, -7] # => 1
#[3] # => 3
#[3, -7] # => -4
#[-7] # => -7
# list3 = [2, 3, -6, 7, -6, 7]
# p second_largest_contiguous_subsum(list3) # => 8 (from [7, -6, 7])
# list4 = [-5, -1, -3]
# p second_largest_contiguous_subsum(list4) # => -1 (from [-1])