0

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)

5
  • 2
    You don't reset i. Use for loops instead. Commented Feb 4, 2020 at 14:47
  • 2
    Also, you should increment j unconditionally. Commented Feb 4, 2020 at 14:49
  • I then see the arrayoutofbounds error in the debugger beside (again which is what id expect) You shouldn't be expecting that. And if so, there should be a mecanism to catchthe exception Commented Feb 4, 2020 at 14:49
  • Should i be using For loops for each loop or just the interior/exterior loop? also thanks Commented Feb 4, 2020 at 14:51
  • When you fix your error, consider that a[i]*a[j] is exactly the same as a[j]*a[i], so there is no need to process both of them. Commented Feb 4, 2020 at 14:53

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.