Arrays 最大利润股票市场算法

Arrays 最大利润股票市场算法,arrays,algorithm,Arrays,Algorithm,对于利润最大的股票市场问题(使用O(nlogn)方法或O(n)方法),我如何返回数组A中每天利润最大的数组,而不是返回数组A中利润最大的一对 最大利润可以定义为在第一天买入,然后在第二天卖出。您可以使用O(n)复杂性来实现这一点。这只是从左到右的一次传球。解决方案来自于 public int getMaxProfit(int[]股价昨日){ //确保我们至少有两个价格 if(股票价格当日长度

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


最大利润可以定义为在第一天买入,然后在第二天卖出。

您可以使用
O(n)
复杂性来实现这一点。这只是从左到右的一次传球。解决方案来自于

public int getMaxProfit(int[]股价昨日){
//确保我们至少有两个价格
if(股票价格当日长度<2){
抛出新的IllegalArgumentException(“获得利润至少需要2个价格”);
}
//我们将贪婪地更新minPrice和maxProfit,因此我们初始化
//他们以第一个价格和第一个可能的利润购买
int minPrice=股票价格昨日[0];
int maxProfit=stockPricesYesterday[1]-stockPricesYesterday[0];
//从第二次(索引1)开始
//我们不能在第一时间出售,因为我们必须先购买,
//我们不能同时买卖!
//如果我们从指数0开始,我们会尝试在时间0买入/卖出。
//这将使利润为0,如果我们的
//maxProfit应该是/负/--我们将返回0!
对于(int i=1;i
其他一些变体和


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

您尝试过什么?你可以为这个家庭作业寻求帮助吗?除了O(n^2)暴力之外,我试着将每个元素与左子数组、右子数组中的后续元素进行比较,并将左子数组中的每个元素与右子数组中的每个元素进行比较。但仍然不确定如何获得O(n)。只要我一提,我就能得到帮助。我将编辑这篇文章,询问提示而不是答案。谢谢,不要分而治之。你应该能够在一次从左到右的传球中做到这一点。有一种简单的方法可以跟踪您迄今为止看到的最佳价格和最佳利润。在我们能够帮助您之前,我们需要您回答您的问题,并提供:(1)一个,(2)您得到的错误或有问题输出的详细描述,以及(3)您的目标。看,下次就行了。谢谢。我需要返回一个数组,该数组提供每天的最大利润(第一天买入,第二天卖出),而不仅仅是总的最大利润。有什么想法吗?
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;
}