0

Is there a way to only return the min/max values of an array where the min is in a lower index position than the max?

For instance, let's say we have:

array = [10, 12, 5, 3, 20, 1, 9]

If we did .minmax on this array we would get the following:

array.minmax
=> [1, 20]

However, I'm only interested in getting the minimum value that has a lower index than the maximum value, in this case:

=> [3, 20]

I've been trying to think about different ways to do this but haven't had much luck. I tried to find a way to get the min/max values where the difference between the two returns a negative value but couldn't find a way to do that.

Edit: To clarify, this is essentially intended to be a stock picker. The array elements are the prices of a stock each day. I'm interested in maximizing the difference between a min/max in the array (buy on the day when stock = 3, sell on the day when stock = 15). The values may not be the absolute min or max.

4

1 回答 1

0

我会尝试:

array[0..array.index(array.max)].minmax

所以只需将 minmax 应用于数组的第一个和最大值的索引之间的元素。

要返回索引值,只需使用 map 遍历 minmax 数组并在新数组中获取它们的索引:

array         = [10, 12, 5, 3, 20, 1, 9]
min_max_array = array[0..array.index(array.max)].minmax
min_max_index = min_max_array.map{|v| array.index(v)}
于 2015-08-12T16:13:14.407 回答