【发布时间】:2020-02-13 20:32:41
【问题描述】:
我的任务:
实现一个方法#stock_picker,它接收一组股票价格,每个假设日都有一个。它应该返回一对代表最佳买入日和最佳卖出日的日期。天数从 0 开始。
> stock_picker([17,3,6,9,15,8,6,1,10]) => [1,4] # for a profit of $15 - $3 == $12快速提示:
- 您需要先购买才能出售
- 注意边缘情况,例如最低日是最后一天或最高日是第一天。
我的代码:
def stock_picker(array)
largest = 0
smallest = 1000
largest_index = 1
smallest_index = 0
array.each { |small|
array.each { |large|
if small < smallest && array.index(small) < largest_index
smallest = small
smallest_index = array.index(small)
#puts 'smallest = ' + smallest.to_s
end
if large > largest && array.index(large) > smallest_index
largest = large
largest_index = array.index(large)
#puts "largest = " + largest.to_s
end
}
}
[smallest_index, largest_index]
end
p stock_picker([17,3,6,9,15,8,6,1,10])
p stock_picker([4,6,9,34,28,12,2,16,8,44])
p stock_picker([8, 5, 3, 6 ,8, 56, 43, 76, 54, 9])
p stock_picker([6, 2, 7, 3, 1, 7, 3, 8, 4, 9])
p stock_picker([99, 88, 77, 66, 55, 44, 33, 22, 11, 99])
我的代码适用于前 4 次测试,但在最后一次测试中卡在 [0,1] 上。 我不明白为什么嵌套的 .each 不会遍历分配的值。如果我更改最后一个 '99',它运行良好。
谁能向我解释我做错了什么?
【问题讨论】:
-
我给你一些提示:1)
Array.index只会找到第一次出现。如果您有多次出现(例如 99 两次),它只会找到第一个 99。2)您可能希望使用方法Array.each_with_index而不是Array.each。这将消除调用Array.index的需要,无论如何您都不能在此处使用它,因为它不适用于多次出现。 -
哦,太好了,是在hackerrank还是其他网站上?可以链接吗?
-
@Casper 非常感谢您的回复。这正是我理解我的问题所需要知道的。
标签: ruby