Stock Time Machine
Obtuvo acceso a un conjunto de datos, tomorrowStocks
que contiene los precios de las acciones de su negocio favorito en el NASDAQ. Este conjunto de datos es un contenedor indexado por minutos después de la apertura. Cada índice contiene el precio de la acción en ese momento.
// Assume the stock market opens at 9:30AM EDT
// tomorrowStocks[] contains the prices of your target stock.
// If the stock is $22 @ 10:30AM EDT
tomorrowStocks[60] == 22
Salida
Su tarea consiste en determinar el mejor resultado posible de 1 purchase
y 1 sale
de la 1 stock
del conjunto de datos dado.
Gotchas
- Debe comprar y vender exactamente 1 acción.
- No puede comprar y vender en el mismo intervalo de tiempo.
- Debe comprar antes de vender.
Datos de prueba
[1,2,3,4,5] # 4
[1,99,2,105] # 104
[99,1,99,100] # 99
[99,1,1,2,1,3] # 2
[5,4,3,3,1] # 0
[5,4,3,1] # -1
[5,2,1] # -1
[5,4,1] # -1
[55,45,20,1] # -10
[5,1] # -4
[10,7,5,1] # -2
[7] # Invalid input -- assume size >= 2
Este es un código de golf ; ¡envía la respuesta más corta en tu idioma favorito!
[5,4,3,1]
usted puede, pero para5
y se venden por4
o para comprar4
y vender para3
obtener el resultado óptimo de-1
.Respuestas:
05AB1E , 4 bytes
Usando el enfoque de FryAmTheEggman . Código:
Explicación:
Utiliza la codificación CP-1252 . Pruébalo en línea! .
fuente
Python 2, 46 bytes
Pruébalo en Ideone .
Cómo funciona
Este es un enfoque recursivo que aprovecha las comparaciones de tipo mixto maravillosamente perversas de Python 2.
El mejor resultado posible es la diferencia del máximo de la lista con su primer elemento eliminado y ese primer elemento, u otra diferencia que no involucre al primer elemento.
Después de extraer el primer elemento con
x.pop(0)
(que lo elimina permanentemente de x ), calculamosx.pop(0)-max(x)
. Tenga en cuenta que esta diferencia tiene el signo "incorrecto".Si la lista actualizada x todavía contiene al menos dos elementos,
x[1:]
genera una lista no vacía y laand
reemplaza con el negativo de una llamada recursiva, calculada como-f(x)
. Una vez que hay muy pocos elementos para continuar, sex[1:]and-f(x)
evalúa como una lista vacía.To select the maximal outcome, we take the minimum of the difference and the negative of the recursive call (or
[]
). Since all integers are strictly less than[]
,min
will simply return its left argument if the right one is[]
.Finally, the unary minus
-
corrects the sign of the computed outcome.fuente
MATL, 7 bytes
Try it online! Or verify all test cases.
fuente
Jelly, 5 bytes
Try it online! or verify all test cases.
How it works
fuente
IŒṡS€Ṁ
Almost same length, it's too bad doing usingṀ
before summing occasionally gives the wrong answer...Pyth, 9
Try it here or run a Test Suite.
Finds the consecutive differences between each element, then finds each substring of that array. Finally, sum the elements and return the maximal one.
Explanation:
It was mentioned to me that that this algorithm works isn't entirely intuitive. Hopefully this example will illustrate why this algorithm works:
fuente
Pyth, 9
Yay pfns!
fuente
_hS-M.cQ2
is equivalent.-
's argument order... since I have to use_hS
and can't useeS
PowerShell v2+, 58 bytes
Takes input
$n
, pipes each element into a loop|%{...}
. Each iteration, we slice$n
based on pre-incremented++$i
to the end of the input array,|sort
that, and take the maximal[-1]
, then subtract the current element$_
. We then|sort
all of those differences, and again take the maximal[-1]
.Tosses out a verbose array-index error, because we try to slice past the end of the array. But, since STDERR is ignored by default, we don't care.
fuente
JavaScript (ES6),
5754 bytesIn JavaScript it's easier to take the max of the remainder of the array and subtract the current element. (In the case of the last element the result will still be -Infinity.) Edit: Saved 3 bytes thanks to @CharlieWynn.
fuente
with
(which doesn't help in this case).J, 21 bytes
Takes an array of values as an argument and returns the result.
Explanation
fuente
Java, 141 bytes
The lambda accepts an ArrayList and returns an Integer.
Ungolfed code with test cases:
As far as I know, Java doesn't have a way to look forward in a stream, and manipulating the method from which the stream is generated produces strange results. So doing
a.remove(0)
inside a map horribly breaks the stream.fuente
VBA, 154
Takes in the input in column A starting in A1, outputs in C1. Must be run with the last cell in A selected. Note that Excel auto-adds the spaces between terms in VBA, otherwise this could be golfed further.
fuente
Java, 116
Another java solution, i used this one to prove that, streams might looks nice, but not always useful for golfing.
there is lot of space for improvements in this solution
fuente
Clojure, 99 bytes
Splits input list at first position then second and so on, so we get a list which looks like this:
[[[n1][n2 ... nk]][[n1 n2][n3 ... nk]]...[[n1...n(k-1)][nk]]]
then for each pair subtracts minimum of the first elements from max of the second element and then find max from them. Would be shorter if Clojure'smin
max
were taking sequences rather than any number of arguments.See it online: https://ideone.com/b2nllT
fuente
ruby, 52 bytes
pops possible sell prices and look at all of the previous to find profit. Then gets max profit.
fuente
C,
10199 BytesInput: null terminated array. E.g. {1,2,3,4,5,0}
Output: returns the best outcome
You can save 8 bytes (
9391 total) if you never want to lose money:fuente
R,
5844 bytesungolfed
EDIT: changed function. original below.
or, if you're willing to put up with a bunch of warning messages, get rid of the -2 after length, for 56 bytes.
And if you feel like not trading and losing money when that's the only possibility, you can get down to 52
fuente
f=
isn't needed.