Javonne
Javonne

Reputation: 39

What is the issue with my maximum product algorithm

Here is the code:

public static int MaxProduct(int... a){  // the max possible product from an array
    int i = 0;
    int j = 0;
    int m = 0;
    int n = a.length;
    while (i<n){
        j++;
        while(j<n ){
            if (a[i]*a[j] > m){
                m = a[i]*a[j];
                j++;
            }
        }
        i++;
    }
    return m;
}


System.out.println(MaxProduct(1,2,3,4,5));

The algorithm seems to work as expected (after check and making a table of the debugger). For the first index of an array it checks all possible products and edits m accordingly from 1 through to 5. And then once j is equal to 5 a[j]understandably is out of bounds since there are only 5 elements in the array

I then see the arrayoutofbounds error in the debugger beside (again which is what id expect) but instead of i increasing, and the second while loop starting the cycle again, a[i] stays as 1, the algorithm concludes, and i get the output 5

How do i get this to output 20 (4x5)

Upvotes: 0

Views: 72

Answers (1)

Govinda Sakhare
Govinda Sakhare

Reputation: 5749

You need to make two changes. Check below 2 TODOs.

public static int MaxProduct(int... a) {  // the max possible product from an array
    int i = 0;
    int j = 0;
    int m = 0;
    int n = a.length;
    while (i < n) {
        j = i + 1;  // TODO: 1
        while (j < n) {
            if (a[i] * a[j] > m) {
                m = a[i] * a[j];
            }
            j++; // TODO:2
        }
        i++;
    }
    return m;
}

Upvotes: 2

Related Questions