Skip to content

Commit efbf759

Browse files
committed
Largest triple product.
1 parent a7f2406 commit efbf759

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed

Problems/largest_triple_products.rb

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
=begin
2+
Signature
3+
int[] find_max_product(int[] arr)
4+
Input
5+
n is in the range [1, 100,000].
6+
Each value arr[i] is in the range [1, 1,000].
7+
Output
8+
Return a list of n integers output[0..(n-1)], as described above.
9+
Example 1
10+
n = 5
11+
arr = [1, 2, 3, 4, 5]
12+
output = [-1, -1, 6, 24, 60]
13+
The 3rd element of output is 3*2*1 = 6, the 4th is 4*3*2 = 24, and the 5th is 5*4*3 = 60.
14+
Example 2
15+
n = 5
16+
arr = [2, 1, 2, 1, 2]
17+
output = [-1, -1, 4, 4, 8]
18+
The 3rd element of output is 2*2*1 = 4, the 4th is 2*2*1 = 4, and the 5th is 2*2*2 = 8.
19+
=end
20+
21+
22+
class Heap
23+
attr_accessor :values
24+
def initialize
25+
@values = []
26+
end
27+
28+
def push(value)
29+
@values.push(value)
30+
end
31+
32+
def pop(values)
33+
@values.pop
34+
end
35+
36+
def size
37+
@values.size
38+
end
39+
40+
def sum
41+
@values.inject(1){|s, i| s*i}
42+
end
43+
44+
def bubble_up
45+
i = @values.size-1
46+
while(i >= 1)
47+
p = (i-1)/2
48+
if @values[p] > @values[i]
49+
@values[p], @values[i] = @values[i], @values[p]
50+
end
51+
i = p
52+
end
53+
end
54+
55+
def heapify(i)
56+
min = i
57+
l = (2*i)+1
58+
r = (2*i)+2
59+
60+
if(l < @values.size && @values[l] < @values[min])
61+
min = l
62+
end
63+
64+
if(r < @values.size && @values[r] < @values[min])
65+
min = r
66+
end
67+
68+
if(min != i)
69+
@values[i], @values[min] = @values[min], @values[i]
70+
self.heapify(min);
71+
end
72+
end
73+
74+
def remove_min
75+
@values[0] = @values[@values.size-1]
76+
@values.pop
77+
self.heapify(0)
78+
end
79+
end
80+
81+
def find_max_product(arr)
82+
min_heap = Heap.new
83+
output = []
84+
arr.each do |v|
85+
if(min_heap.size < 2)
86+
min_heap.push(v)
87+
min_heap.bubble_up
88+
output.push(-1)
89+
else
90+
min_heap.push(v)
91+
min_heap.bubble_up
92+
min_heap.remove_min if min_heap.size > 3
93+
output.push(min_heap.sum)
94+
end
95+
end
96+
return output
97+
end
98+
99+
# Call find_max_product() with test cases here
100+
p find_max_product([1,2,3,4,5])

0 commit comments

Comments
 (0)