【问题标题】:Lookup `indexOf`? [duplicate]查找`indexOf`? [复制]
【发布时间】:2017-10-20 20:50:03
【问题描述】:
   char first  = target[targetOffset];
    int max = sourceOffset + (sourceCount - targetCount);

    for (int i = sourceOffset + fromIndex; i <= max; i++) {
        /* Look for first character. */
        if (source[i] != first) {
            while (++i <= max && source[i] != first);
        }

        /* Found first character, now look at the rest of v2 */
        if (i <= max) {
            int j = i + 1;
            int end = j + targetCount - 1;
            for (int k = targetOffset + 1; j < end && source[j] ==
                     target[k]; j++, k++);

            if (j == end) {
                /* Found whole string. */
                return i - sourceOffset;
            }
        }

【问题讨论】:

  • 不,只要最小的数字在最大的数字之前,我试图获得值之间的最大差异。 max 行不通,因为价格从最高数字开始?我不知道如何比较数组中的值?
  • 最大利润应该是在 11 时做空并在 1 时补仓。;-) 看起来像 reduce 的工作。
  • @jfriend00 编辑了问题以删除效率 - 让我知道这是否足够如果您不同意,我将关闭 q!
  • 我认为这个问题与.indexOf() 没有任何关系,您的标题似乎表明您认为您必须使用它。这是需要使用.indexOf()的作业题吗?
  • @jfriend00 哈哈,我没有作业..

标签: javascript algorithm ecmascript-6


【解决方案1】:

这可以在 O(n) 中解决:

function getMaxProfit(prices) {
    let min = prices[0];
    let profit = 0;
    for (let i = 1; i < prices.length; i++) {
        if (prices[i] < min)
            min = prices[i];
        if (prices[i] - min > profit)
            profit = prices[i] - min;
    }
    return profit;
}

这个想法是从头到尾扫描以获得位置 i 之前的最佳最小值。此最小值用于计算您在第 i 天(立即)卖出可获得的最佳利润,并将此金额与全局(最大)利润进行比较。

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 2018-07-22
    • 2018-06-18
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 2012-04-03
    相关资源
    最近更新 更多