【问题标题】:Elements of Programming 6.4 Two-shot and k-shot strategy algorithm编程要素 6.4 two-shot 和 k-shot 策略算法
【发布时间】:2013-09-11 18:47:38
【问题描述】:

很难理解这两种 shot 和 k-shot 策略算法。问题又来了:

Q1) arr 是一个长度为 n 的数组。计算 A[j0]-A[i0] + A[j1]-A[i1] 的最大值,条件是 i0

Ans) 我们可以在 O(n) 中进行单次(即最大利润买卖股票)。我们可以应用相同的技术 从 0..j 中找到最大值,从 j..n 中找到最大值。这将是 O(n2) 解决方案。

 Elements of Programming interviews book suggests a way of doing this in O(n) time by:
 doing a forward iteration and storing solution for A[0:j] such that 1<=j<=n-1  and then a backward iteration for A[j:n-1] such that 0<=j<=n-2 and then combining the two results.  Does anyone have any idea how this can be done?

Q2) 你会怎么做k-shot?

谢谢!!

【问题讨论】:

    标签: algorithm


    【解决方案1】:

    第一季度

    让我们先在O(n) 中解决这个更简单的问题:找到i0 &lt; j0 使得A[j0] - A[i0] 最大化。

    对于每个j0,我们需要找到0, 1, ..., j0 - 1 的最小值并将A[j0] - this minimum 与全局最大值进行比较。这很容易通过计算最小值来完成。

    现在,对于您的原始问题,我们还需要 i1 &lt; j1 以使 A[j1] - A[i1] 最大化。或者,对于每个i1,我们需要找到j1 &gt; i1,使得A[j1] - A[i1]最大化。

    让:

    min[i] = minimum in [0, ..., i]
    max[i] = maximum in [i, ..., n - 1]
    

    所以现在我们需要i &lt; j 使得A[i] - min[i - 1] + max[j + 1] - A[j] 最大化。这可以通过计算来完成,O(n):

    max1[i] = max{A[1] - min[0], A[2] - min[1], ..., A[i] - min[i - 1]}
    max2[i] = max{max[i + 1] - A[i], max[i] - A[i - 1], ...max[1] - A[0]}
    

    然后只取max1[i - 1] + max2[i] 的最大值超过所有i &gt;= 2

    【讨论】:

    • @adne - 不客气,但我不知道如何做 Q2。如果您也想等待答案,可以不接受。
    猜你喜欢
    • 2013-08-14
    • 2013-11-03
    • 2021-08-17
    • 2010-10-26
    • 2018-04-05
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    相关资源
    最近更新 更多