Search code examples
algorithmsortingpseudocodediscrete-mathematics

Pseudocode for brute-force algorithm to find largest product of two numbers in a list


I am trying to come up with a pseudocode brute-force algorithm that finds the largest product of two numbers in a list a[sub1] to a[subn], with n greater than or equal to 2. Right now, I have

for ( i = 1 to n -1)

    a[subi] = a[subi-1] * a[subi+1]

    for (j = a[sub j+1] to n)

        a[sub j] = a[sub j-1] * a[sub j+1]

    end for

end for

return `a[sub i]`

return `a[sub j]`

However, this is not correct. I feel like there's something simple I'm missing here, but I can't figure it out. Any ideas? Thanks in advance.


Solution

  • largest_product = a[1] * a[2]
    
    for ( i = 1 to n -1)
        for (j = i + 1 to n)
            product = a [i] * a [j]
    
            if (product > largest_product)
                largest_product = product
            end if
        end for
    
    end for
    
    return largest_product
    

    Edit:

    The comments to your question suggest a more efficient solution in linear time.

    Implementation will follow up.