user2623706
user2623706

Reputation: 527

Max subarray - get output formatted correctly

I am trying out the classic max subarray problem. I am outputting the correct arrays but I want it to be formatted differently. Here is my code:

def max_subarray(input)
  return input if input.length == 1

  max = 0
  subarrays = []

  input.each do |element|
    current_subarray = []
    if max + element > element
      current_subarray << subarrays[-1]
      current_subarray << element
      subarrays << current_subarray
      max += element
    else
      subarrays << [element]
      max = element
    end
  end

  subarrays.each do |s|
    print s
    puts ''
  end
end

max_subarray([-2, -3, 4, -1, -2, 1, 5, -3])

Which gives me the following output:

[-2]
[-3]
[4]
[[4], -1]
[[[4], -1], -2]
[[[[4], -1], -2], 1]
[[[[[4], -1], -2], 1], 5]
[[[[[[4], -1], -2], 1], 5], -3]

While these are the numbers that I want I want them to be one array for each line. Not nested arrays. Any ideas?

Thank you,

p.s. once I get this part down it is a small step to find the one with the max sum.

Upvotes: 1

Views: 74

Answers (1)

Nick Veys
Nick Veys

Reputation: 23949

I may be misinterpreting your question, but you may be looking for flatten.

...
subarrays.each do |s|
  print s.flatten
  puts ''
end
...

Which results in:

(nick@monster)-(~/Desktop)
(504)⚡️ ruby derp.rb 
[-2]
[-3]
[4]
[4, -1]
[4, -1, -2]
[4, -1, -2, 1]
[4, -1, -2, 1, 5]
[4, -1, -2, 1, 5, -3]

Upvotes: 1

Related Questions