連続した整数の和で最大となるものを表示。
正答率69%
((246.0/(246+111))*100).round
設問
Write a program to determine the largest sum of contiguous integers in a list.
Input sample:
The first argument will be a text file containing a comma separated list of integers, one per line. e.g.
-10, 2, 3, -2, 0, 5, -15 2,3,-2,-1,10
Output sample:
Print to stdout, the largest sum. In other words, of all the possible contiguous subarrays for a given array, find the one with the largest sum, and print that sum.
e.g.
8 12
やってみた
#!/usr/bin/env ruby def sum_of(integers) sums_all = [] integers.each_with_index do |_, i| integers[i..-1].inject(0) do |sum, integer| sums_all << sum += integer sum end end sums_all.max end ARGF.lines do |line| puts sum_of(line.chomp.split(',').map(&:to_i)) end
each_with_indexが強引だ。
参考
RubyでSum of integersを解く-CodeEval - hp12c
candidates = [] begin nums.inject(0) { |mem, i| candidates << mem += i; mem } end while nums.shift
Array#shiftしながらwhileで回しています。
あとcandidatesという名前もいいですね。