Created
September 19, 2016 19:00
-
-
Save anil826/0d5ddfde9d8ac3afaf5aea240c623864 to your computer and use it in GitHub Desktop.
Find the contiguous subarray within a onedimensional
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Write a RoR program to find the contiguous subarray within a onedimensional | |
# array of | |
# numbers (containing at least one positive number) which has the largest sum. For | |
# example | |
# for the sequence of values −2, 1, −3, 4, −1, 2, 1, −5, 4; the contiguous subarray with the | |
# largest sum is 4, −1, 2, 1, with sum 6. | |
# The program should run as follows is user entry>: | |
# Enter the array : 2 | |
# 1 3 | |
# 4 1 | |
# 2 1 5 | |
# 4 | |
# Largest SubArray | |
# Start Index: 3 | |
# Length: 4 | |
# Sum: 6 | |
# Elements: 4 1 | |
# 2 1 | |
puts "Welcome to Test ::: Input size of array" | |
arrayNumber = gets | |
puts "Size of your array is : #{arrayNumber}" | |
length = [] | |
sum = [] | |
data = [] | |
currSum=0 | |
startIndex=0 | |
arrayNumber.to_i.times do |f| | |
puts " Number:: #{f}" | |
data << gets.to_i | |
end | |
max = data[0] | |
puts "--------------------------------------------" | |
puts "data ::: #{data}" | |
puts "--------------------------------------------" | |
if(data.max >=0) | |
data.each_with_index do |f,i| # starging of array loop | |
currSum = f # init with first element of sub array | |
length[startIndex] = 1 # init lenght of sub array | |
sum[startIndex] = f # sum of sub array | |
for k in (i+1)..data.length # start of sub array loop | |
currSum = currSum + data[k].to_i | |
if(sum[startIndex].to_i < currSum) | |
for t in (i+1)..k # for checking the positive element in sub array. | |
if(data[t].to_i >=0) | |
length[startIndex] = k - i +1 # length of sub array | |
sum[startIndex] = currSum # sum of sub array | |
break | |
end | |
end | |
end | |
end | |
startIndex = startIndex +1 | |
end | |
max_sum = sum.max | |
get_index = sum.find_index(max_sum) | |
value_of_length = length[get_index] | |
puts "startIndex : : #{get_index}" | |
puts "length :: #{value_of_length}" | |
puts "Max ::: #{max_sum}" | |
print "Elements :: " | |
(get_index..(value_of_length+get_index -1)).each do |p| | |
print data[p].to_s + " " | |
end | |
puts "" | |
else | |
puts "There is no positive number" | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment