Please help me to understand this iteration


i have started again recently with python and im just abit confused about this iteration:

def maxProduct(array):
    arrayLength = len(array)
    if(arrayLength < 2):
        print("No pairs exists")
    x = array[0]; y = array[1]

    for i in range(arrayLength):  

        ********  for j in range(i + 1, arrayLength):  **************
            if(array[i] * array[j] > x * y):
                x = array[i]; y = array[j]

    return x, y

nums = [1,2,3,4,7,0,8,4]
print("Original array:", nums)
print("Maximum product pair is:", maxProduct(nums))

nums = [0,-1,-2,-4,5,0,-6]
print("\nOriginal array:", nums)
print("Maximum product pair is:", maxProduct(nums))

now i please need help with the for j in range thats in the line with stars. I want to know why the start of the range function is i + 1 and not 0 like the for in loop above it?

1 Like

Consider what is the goal of function. Can it use the same number twice to create the pair or not? How would starting second loop from 0 impact goal of the function?

1 Like

if i take the start of range function out the same 2 values get returned. So we start the first for in loop at index 0, we have to start the second for in loop at index 1 to get highest product of a pair of numbers while looping through the array. Am i right? Please correct me if im wrong

1 Like

Yeah, if the start of the second loop would be the same as in first one (or it would be 0) then result might be incorrect and coming form using the same number twice.

1 Like

thanks so much for your assistance

1 Like

Hello there,

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like