Skip to content

Commit 59efea1

Browse files
author
piotrzientara
committed
equi leaders, correct solution without performance 50%
1 parent 24708bb commit 59efea1

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

equiLeader/equi_leader.rb

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,38 @@
11
class EquiLeader
22
def solution(array)
3+
equi_leaders = []
4+
array.size.times do |index|
5+
first_leader = find_leader((array[0..index]))
6+
if first_leader != -1
7+
second_part = array[(index+1)..-1]
8+
second_leader = find_leader(second_part)
9+
if second_leader == first_leader
10+
equi_leaders << index
11+
end
12+
end
13+
end
14+
equi_leaders.size
15+
end
316

17+
def find_leader(array)
18+
size = 0
19+
value = array.first
20+
array.each do |el|
21+
if (size == 0)
22+
size += 1
23+
value = el
24+
else
25+
value != el ? size -= 1 : size += 1
26+
end
27+
end
28+
candidate = -1
29+
candidate = value if (size > 0)
30+
leader = -1
31+
count = 0
32+
array.each do |el|
33+
count += 1 if (el == candidate)
34+
end
35+
leader = candidate if (count > array.size / 2)
36+
leader
437
end
538
end

equiLeader/equi_leader_test.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
describe EquiLeader do
44
it 'should find equi leader' do
5-
array = [4, 3, 4, 4, 4, 2, 3, 3]
5+
array = [4, 3, 4, 4, 4, 2]
66
expect(subject.solution(array)).to eql(2)
77
end
88
end

0 commit comments

Comments
 (0)