有关Java中的最大值/利润子数组问题的问题

时间:2019-05-28 15:57:07

标签: java

这是数组...

int[] array = new int[]{4,-1,-2,3,5,-7,1,0,0,-2,4};

我们需要查看是否可以从前一天开始购买股票。因此,我们应该在-1买入,在5卖出。这将带来6的利润。

    int max = Integer.MIN_VALUE;
    int maxDiff = Integer.MIN_VALUE;
    int diff = 0;
    int bottom = array[0];

    for (int i = 1; i < array.length; i++) {
        diff += array[i] - array[i - 1];

        System.out.println(diff);
        if (diff > maxDiff) {
            maxDiff = diff;
            max = array[i];
        }

        if (array[i] < bottom) {
            bottom = array[i];
            diff = 0;
        }
    }

    int maxx = max - maxDiff;
    System.out.println("Buy at " + maxx + " Sell at " + max);

这就是说我应该在-7买入,然后在4卖出。这不是真的。 如果我们在-7买入,价格将上升1,然后保持不变,保持不变,下降2,然后上升4。这不会为我们带来最大的利润。

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

由于数组包含价格走势,因此假设起始价格并从中计算最小/最大

int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int price = 100;
int dayIn = 0;
int dayOut = 0;

for (int i = 0; i < array.length; i++) {
    price += array[i];
    if (price > max) {
        max = price;
        dayOut = i;
    } 
    if (price < min) {
        min = price;
        dayIn = i;
    } 
}
if (max > min && dayIn < dayOut) { 
    System.out.printf("Buy for %d at day %d and sell on day %d for %d. Profit: %d\n", min, (dayIn + 1), (dayOut+1), max, max - min);
} else {
    System.out.println("No trade opportunity found");
}