在递归时保持天数指数

时间:2018-04-24 23:30:47

标签: java

在下面的代码中,我试图找出哪个是买卖股票的最佳日子。然而,我只能计算在正确的日子买卖的利润,但我无法找到日期(指数),因为它们在递归中丢失了。我不想使用任何静态变量。我想的唯一解决方案是添加一个新的私有方法,以保持正确的日子。

public class Stock {

public static int maximum(int[] half) {
    int max=half[0]; 
    int index=0;
    for (int i=1; i<half.length; i++) {
        if (half[i]>max) {
            max = half[i];
            index=i;
        }
    }

    return max;
}
public static int minimum(int[] half) {
    int min=half[0]; 
    int index=0;
    for (int i=1; i<half.length; i++) {
        if (half[i]<min) {
            min = half[i];
            index=i;
        }
    }

    return min;
}

private static int maxProfit(int[] stock) {
    if (stock.length<= 1)
        return 0;

    int left[] = Arrays.copyOfRange(stock, 0, stock.length/2);
    int right[] = Arrays.copyOfRange(stock, (stock.length/2), stock.length);

    int maxLeft = maxProfit(left);
    int maxRight = maxProfit(right);


    int bothSides = maximum(right) - minimum(left);

    return Math.max(Math.max(maxLeft,maxRight), bothSides);

}

public static void main(String[] args) {

    int[] stock_t = { 13, 5, 2, 12, 3, 15 };

    int fi = maxProfit(stock_t);
    System.out.println(fi);
}

}

1 个答案:

答案 0 :(得分:1)

  

我想保留上次更新的天数值

您可以向类中添加一个实例变量,以保留上次更新的值:

public class Stock{
    private int days;

    public int getDays(){
        return days;
    }
}

要保留计算后的天数值,请在方法退出前更新值:

//In Stock class
public int maximum(int[] half) {    //Make this an instance method (remove static)
    int max=half[0]; 
    int index=0;
    for (int i=1; i<half.length; i++) {
        if (half[i]>max) {
            max = half[i];
            index=i;
        }
    }
    days = index;                   //update before method exits
    return max;
}

您也可以在适当的地方更新days

获取天数值:

public static void main(String[] args) {

    int[] stock_t = { 13, 5, 2, 12, 3, 15 };
    Stock s = new Stock();              //create Stock object
    int fi = s.maxProfit(stock_t);      //calculations will update days attribute
    System.out.println(s.getDays());    //get days according to last calculation
}

你的所有方法都是静态的,在实现方面对我来说似乎有点奇怪。如果您的Stock类应该作为创建Stock对象的模板,并且每个单独的Stock对象都保留其自己的状态,那么您的方法和属性更适合声明为{{ 1}}。

如果要将non-static类用作仅调用方法的实用程序类,则这些方法可以是Stock。但根据你的问题,情况似乎并非如此。

相关问题