简体   繁体   中英

What is the advantage of initializing int maxValue = Integer.MIN_VALUE in Dynamic Programming?

To precisely ask you this question, What is the advantage of initializing int max_val = Integer.MIN_VALUE over int max_val = price[i-1]?

This would seem a trivial DP problem. But, I need your help. General DP problems start by initializing max_val as Integer.MIN_VALUE. I know this is a standard way.

But, I've figured out there is not wrong setting max_val as price[i-1].

eg I got 22 with arr = {1 5 8 9 10 17 17 20 }, and cutRod(arr, 8).

I got 24 with arr = {3 5 8 9 10 17 17 20}, and cutRod(arr, 8).

public class RodCutting {
    public static void main(String[] args) {
        int[] arr = new int[] {2, 5, 13, 19, 20};
        int size = arr.length;
        int result = cutRod(arr, size);
        System.out.println("Maximum Obtainable Value is " + result);
    }

    private static int cutRod(int[] price, int n) {
        int val[] = new int[n+1];
        val[0] = 0;

        for (int i = 1; i <= n; i++) {
            int max_val = price[i-1]; // previously, int max_val = Integer.MIN_VALUE;
            for (int j = 0; j < i; j++) 
                max_val = Math.max(max_val,  val[j+1]+ val[i - j - 1]); 
                // previously, max_val = Math.max(max_val, price[j] + val[i - j - 1]);

            val[i] = max_val;
        }
        return val[n];
    }
}

Thanks in advance.

In the general sense, there is no strong "advantage" to initializing a local variable to Integer.MIN_VALUE ... versus any other value that is guaranteed to be less or equal to the max you are computing.

In this case, this tweak clearly makes no difference to the computational complexity. You still need to perform the inner loop j - i times. It might affect the branching inside the Math.max call, but I doubt that the performance difference will be significant... Either way, the only way to be sure would be careful benchmarking with a large sample set of representative inputs. And that will only give you an answer for this particular problem.

However, you know that Integer.MIN_VALUE must be less or equal to that the actual maximum. So using that value means that there is one less thing that needs to be proven in a correctness proof. (Or to put it another way, it may make your code easier to understand.)


But here's the thing. If you are going to try tweaks like this, you should be reasoning about it yourself ... not looking for empirical "advantages", or asking someone else to do the reasoning for you. And if you are doing this for performance reasons, you should also be benchmarking.

And if it is all too much work... take Knuth's advice on premature optimization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM