Skip to content

Instantly share code, notes, and snippets.

@DariaUlanova
Last active April 13, 2017 15:23
Show Gist options
  • Save DariaUlanova/ff06f7db9957b5aad0c8f803a304d7f9 to your computer and use it in GitHub Desktop.
Save DariaUlanova/ff06f7db9957b5aad0c8f803a304d7f9 to your computer and use it in GitHub Desktop.
def solution(array)
max_distance = 0
indexes = {}
array.each_with_index do |item, index|
if indexes.keys.include?(array[index])
max_distance = [max_distance, index - indexes[array[index]]].max
else
indexes[array[index]] = index
end
end
max_distance
end
class Task
def solution array
sum = array.inject(:+)
n = array.count
left_sum = 0
array.each_with_index do |el, i|
sum -= array[i]
return i if left_sum == sum
left_sum += array[i]
end
return -1
end
def solution2(a)
n = a.length
result = 0
for i in 0 .. (n - 1)
for j in 0 .. (n - 1)
if (a[i] == a[j]) then
if (i - j).abs > result then
result = (i - j).abs
end
end
end
end
return result
end
def solution3(array)
max_distance = 0
indexes = {}
array.each_with_index do |item, index|
if indexes.keys.include?(array[index])
max_distance = [max_distance, index - indexes[array[index]]].max
else
indexes[array[index]] = index
end
end
max_distance
end
end
describe Task do
describe 'solution' do
subject { Task.new.solution a }
context '1' do
let(:a) { [-1, 3, -4, 5, 1, -6, 2, 1] }
it { is_expected.to eq 1 }
end
context '2' do
let(:a) { [1,2,3,4] }
it { is_expected.to eq -1 }
end
end
describe 'solution2' do
subject { Task.new.solution2 a }
context '1' do
let(:a) { [4,6,2,2,6,6,1] }
it { is_expected.to eq 4 }
end
end
describe 'solution3' do
subject { Task.new.solution3 a }
context '1' do
let(:a) { [4,6,2,2,6,6,1] }
it { is_expected.to eq 4 }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment