arrays - 最大利润股市算法

标签 arrays algorithm

<分区>

对于最大利润股票市场问题(使用 O(nlogn) 方法或 O(n) 方法),而不是返回数组 A 中给出最大利润的对,我如何返回一个数组给出数组 A 中每一天的最大利润?

最大利润可以定义为在第 i 天买入并在随后的一天卖出。

最佳答案

你可以用 O(n) 的复杂度来做到这一点。这只是一次从左到右的传递。解决方案取自here .

public int getMaxProfit(int[] stockPricesYesterday) {

    // make sure we have at least 2 prices
    if (stockPricesYesterday.length < 2) {
        throw new IllegalArgumentException("Getting a profit requires at least 2 prices");
    }

    // we'll greedily update minPrice and maxProfit, so we initialize
    // them to the first price and the first possible profit
    int minPrice = stockPricesYesterday[0];
    int maxProfit = stockPricesYesterday[1] - stockPricesYesterday[0];

    // start at the second (index 1) time
    // we can't sell at the first time, since we must buy first,
    // and we can't buy and sell at the same time!
    // if we started at index 0, we'd try to buy /and/ sell at time 0.
    // this would give a profit of 0, which is a problem if our
    // maxProfit is supposed to be /negative/--we'd return 0!
    for (int i = 1; i < stockPricesYesterday.length; i++) {
        int currentPrice = stockPricesYesterday[i];

        // see what our profit would be if we bought at the
        // min price and sold at the current price
        int potentialProfit = currentPrice - minPrice;

        // update maxProfit if we can do better
        maxProfit = Math.max(maxProfit, potentialProfit);

        // update minPrice so it's always
        // the lowest price we've seen so far
        minPrice = Math.min(minPrice, currentPrice);
    }

    return maxProfit;
}

其他一些变体 herehere .

基本上,如果您对编写算法有疑问,我建议您先查看 GeekforGeeks ,这是一个很棒的门户。

关于arrays - 最大利润股市算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36990463/

相关文章:

c - 如何使用堆栈解决库存跨度问题?

algorithm - 你能检查一下这个替换到目前为止是否正确吗?

javascript - js,$.inArray,未返回预期返回

algorithm - 是二叉树的高度log2(n)

c - 在C中找到数组中最大的十个数字

c - 数组的指针数组在 C 中不起作用

arrays - 在 O(n) 时间内合并具有常量内存的数组的两个排序部分

java - 可以单独访问的多个线程

python - 如何在 Python 中用 numpy 数组列替换数据框列?

java - 尝试创建一种在 Android Java 中格式化十六进制字符串的方法