库存机


35

库存机

您可以访问数据集,tomorrowStocks其中包含您在纳斯达克上喜欢的业务的股票价格。该数据集是一个按打开后分钟数索引的容器。每个指数都包含当时的股票价格。

// 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

输出量

你的任务是确定的最好的结果1 purchase1 sale1 stock从给定的数据集。

陷阱

  • 您必须买卖1只股票。
  • 你可以不买,并在同一时间段销售。
  • 您必须先买卖。

测试数据

[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

这是一个;用您喜欢的语言提交最短答案!


11
欢迎来到PPCG,第一个好问题!:)
FryAmTheEggman

我们是否可以假设输出是确定性的(即始终有一种解决方案绝对是最好的,而且没有任何关系)
MayorMonty 2016年

1
不幸的是,我正在构建的语言的解释器尚未完成,因为它应该能够在4个字节内解决此问题...我需要尽快完成该工作,以免错过很多好问题!
史蒂文H.

1
@SpeedyNinja这实际上是在测试用例中。在测试用例中,[5,4,3,1]您可以选择5并出售44出售3以获得的最佳结果-1
马丁·恩德

1
@Fawful您可以稍后将您的答案添加为不竞争。我绝对有兴趣看到它
CocoaBean

Answers:


14

05AB1E,4个字节

使用FryAmTheEggman的方法。码:

¥ŒOà

说明:

¥     # Calculate the increments of the array.
 Π   # Get all substring of the array.
  O   # Sum the arrays in the array.
   à  # Get the largest sum and implicitly print that.

使用CP-1252编码。在线尝试!


2
该死,我尝试了4种高尔夫语言,却忘记了05AB1E。下次会再学我的:P
FryAmTheEggman

19

Python 2,46个字节

f=lambda x:-min(x.pop(0)-max(x),x[1:]and-f(x))

Ideone上进行测试

怎么运行的

这是一种递归方法,它利用了Python 2精美的错误混合类型比较的优势。

最好的结果可能是列表的最大值与被删除的第一元素和该第一元素的差值,或者与第一元素不相关的另一个差值。

用提取第一个元素x.pop(0)(将其从x中永久删除)后,我们计算x.pop(0)-max(x)。请注意,此差异具有“错误”符号。

如果更新后的列表x仍然至少包含两个元素,则x[1:]生成一个非空列表,并将其and替换为递归调用的负值,计算方式为-f(x)。一旦元素太少而无法继续,则x[1:]and-f(x)求值为空列表。

要选择最大结果,我们采用差值的最小值和递归调用(或[])的负数。由于所有整数都严格小于[]min因此如果右边的整数会简单地返回左边的参数[]

最后,一元负值会-纠正计算结果的符号。


这真是美丽。
MrDuk


8

果冻,5 个字节

Œcḅ-Ṁ

在线尝试!验证所有测试用例

怎么运行的

Œcḅ-Ṁ  Main link. Argument: A (integer array)

Œc     Generate all combinations of two elements of A, in order.
  ḅ-   Convert each pair from base -1 to integer.
       This maps [a, b] to b - a.
    Ṁ  Take the maximum of all computed differences.

IŒṡS€Ṁ几乎相同的长度,在偶尔得出错误答案之前使用非常糟糕……
FryAmTheEggman

7

珀斯9

eSsM.:-Vt

在这里尝试或运行测试套件

查找每个元素之间的连续差异,然后查找该数组的每个子字符串。最后,对元素求和并返回最大值。

说明:

eSsM.:-Vt
eSsM.:-VtQQ   ## Auto-fill variables
      -VtQQ   ## Splat subtraction on each element of zip(Q[1:], Q)
    .:        ## Get all substrings
  sM          ## Sum each list
eS            ## Take the largest number

我曾经提到过,该算法的工作原理并非完全直观。希望此示例将说明此算法为何起作用:

[a, b, c, d]
difference between each element (reversed because of how Pyth does this)
[b-a, c-b, d-c]
"substrings" or each continuous slice
[b-a], [c-b], [d-c], [b-a, c-b], [c-b, d-c], [b-a, c-b, d-c]
sum each
[b-a], [c-b], [d-c], [b-a+c-b], [c-b+d-c], [b-a+c-b+d-c]
simplify
[b-a], [c-b], [d-c], [c-a], [d-b], [d-a]

5

珀斯9

_hS-M.cQ2

耶pfns!

_hS-M.cQ2

     .cQ2 # generate all 2-elements combinations of Q (argument)
   -M     # map-splat with -: for each combination, substract the elements together
  S       # tort
 h        # take the first
_         # absolute value

我相信_hS-M.cQ2是等效的。
FryAmTheEggman'7

@FryAmTheEggman啊,谢谢。现在尝试思考如何才能颠倒-论点的顺序...因为我必须使用_hS并且不能使用eS
Ven

4

PowerShell v2 +,58个字节

param($n)($n|%{($n[++$i..$n.count]|sort)[-1]-$_}|sort)[-1]

接受输入$n,将每个元素传送到一个循环中|%{...}。每次迭代时,我们$n基于预先递增++$i的值对输入数组进行切片|sort,并取最大值[-1],然后减去当前元素$_。然后|sort,我们将所有这些差异全部取为最大[-1]

抛出一个冗长的array-index错误,因为我们试图切入数组的末尾。但是,由于默认情况下会忽略STDERR,因此我们不在乎。


4

JavaScript(ES6),57 54字节

a=>(m=Math.max)(...a.map((x,i)=>m(...a.slice(i+1))-x))

在JavaScript中,取数组剩余部分的最大值并减去当前元素会更容易。(对于最后一个元素,结果仍将是-Infinity。)编辑:由于@CharlieWynn,节省了3个字节。


我认为(M = Math.max)稍后再使用M将为您节省3个字节
Charlie Wynn

@CharlieWynn谢谢,我只尝试了一下with(在这种情况下没有帮助)。
尼尔,2016年

3

J,21个字节

[:>./@;i.@#<@{."_1-/~

将值数组作为参数并返回结果。

说明

[:>./@;i.@#<@{."_1-/~  Input: p
                  -/~  Make a table of all differences between every pair
          #            Get the count of values in p
       i.@             Create a range [0, 1, ..., len(p)-1]
             {."_1     Take that many values from each row of the table
           <@          Box each row of selected values
[:    ;                Unbox and concatenate them
  >./@                 Reduce it by the max and return

2

Java,141个字节

a->java.util.stream.IntStream.range(0,a.size()-1).map(i->a.subList(i+1,a.size()).stream().reduce(Math::max).get()-a.get(i)).max().getAsInt();

Lambda接受ArrayList并返回Integer。

带测试用例的无代码的代码:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.IntStream;

class Test {

    public static void main(String[] args) {
        Function<ArrayList<Integer>, Integer> f = a -> IntStream
            .range(0, a.size()-1)
            .map(i -> a.subList(i+1, a.size()).stream().reduce(Math::max).get() - a.get(i))
            .max()
            .getAsInt();

        System.out.println(f.apply(new ArrayList<>(Arrays.asList(1,2,3,4,5))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(1,99,2,105))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(99,1,99,100))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(99,1,1,2,1,3))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,4,3,3,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,4,3,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,2,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,4,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(55,45,20,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(5,1))));
        System.out.println(f.apply(new ArrayList<>(Arrays.asList(10,7,5,1))));
    }
}

据我所知,Java没有办法在流中进行前瞻,而操纵从中生成流的方法会产生奇怪的结果。因此,a.remove(0)在地图内部进行操作会严重中断流。


1

VBA,154

从A1开始输入A列中的输入,从C1中获取输出。必须与选定A中的最后一个单元格一起运行。请注意,Excel会在VBA中自动在字词之间添加空格,否则可能会导致误解。

Sub s
i = Selection.Row
r = "B1:B" + i-1
Range(r).FormulaArray = "MAX(A2:A$" + i + "-A1)"
Range(r).FillDown
Range("C1").Formula = "MAX(" + r + ")"
End Sub

1

爪哇,116

我用另一个Java解决方案来证明,流看起来不错,但对于打高尔夫球并不总是有用的。

int a(int[]a){int t,d=a[1]-a[0],i,j,l=a.length;for(i=0;i<l;i++)for(j=i+1;j<l;j++){t=a[j]-a[i];d=d<t?t:d;}return d;}

该解决方案还有很多改进空间


1

Clojure,99个字节

(fn[x](apply max(map #(-(apply max(% 1))(apply min(% 0)))(map #(split-at % x)(range 1(count x))))))

在第一个位置分割输入列表,然后在第二个位置依此类推,以此类推,所以我们得到一个看起来像这样的列表:

[[[n1][n2 ... nk]][[n1 n2][n3 ... nk]]...[[n1...n(k-1)][nk]]]然后对于每对从第二个元素的最大值中减去第一个元素的最小值,然后从它们中找出最大值。如果Clojure使用min max序列而不是任何数量的参数,则将更短。

在线查看:https//ideone.com/b2nllT


1

红宝石,52个字节

->a{b=[];(x=a.pop;b+=a.map{|v|x-v})while a[0];b.max}

弹出可能的卖价,并查看所有先前的价格以获利。然后获得最大的利润。


1

C,101 99字节

int i,j,m,h;int f(int*a){m=1<<31;for(;a[i];i++){for(j=i+1;a[j];h=a[j++]-a[i],m=h<m?m:h);}return m;}

输入:以null终止的数组。例如{1,2,3,4,5,0}
输出:返回最佳结果

如果您永远不想亏钱,则可以节省8个字节(共93 91个):

int i,j,m,h;int f(int*a){for(;a[i];i++){for(j=i+1;a[j];h=a[j++]-a[i],m=h<m?m:h);}return m;}

1

R,58 44字节

max(unlist(sapply(seq(y<-scan()),diff,x=y)))

不打高尔夫球

y=scan()                #input
s=1:length(y)           #sequence of same length from 1
l = sapply(s,diff,x=y)  #applies the function diff to each 'lag' in sequence s
                        #and differencing on y
max(unlist(l))          #reforms as vector and finds maximum

编辑:更改功能。原来在下面。

f=function(x)max(max(x[-1]-x[1]),if(length(x)-2)f(x[-1]))

或者,如果您愿意忍受一堆警告消息,请删除长度为-56个字节的-2。

f=function(x)max(max(x[-1]-x[1]),if(length(x))f(x[-1]))

而如果那是唯一的一种可能,那就是不想交易和亏钱,那么您可以降低到52

f=function(x)max(max(x-x[1]),if(length(x))f(x[-1]))

f=不需要。
NoOneIsHere

没有它,@ NoOneIsHere递归将无法工作。我可以使用Recall,但是它能收到的字母多于丢失的字母。
user5957401

哦对不起。我总是想念递归。
NoOneIsHere
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.