Pseudocode of brute-force algorithm that finds largest product of two numbers in a list

1.7k Views Asked by At

This one will require a basic knowledge of some computer science concepts. I am trying to come up with a pseudocode brute-force algorithm that finds the largest product of two numbers in a list $a_1, a_2, ...a_n (n\ge 2)$. Right now, I have:

for ($i=1$ to $n-1$)

$a_i$$ = a_{i-1}$ $ * a_{i+1}$

for ( $j = {j+1}$ to $n$)

$a_j$$ = a_{j-1}$ $ * a_{j+1}$

end for

end for

return $a_i$

return $a_j$

end procedure

However, this is not correct, and I can't figure out what else I'm supposed to do to be able to traverse the entire list, get products of each item in the list, and return the largest products in the lists. I feel like it's something simple I'm missing, but I can't figure it out. Any advice?

2

There are 2 best solutions below

3
On
large = a_1 * a_2
for(i = 1 to n)
    for(j = i+1 to n)
        if(large < a_i * a_j)
            large = a_i * a_j

At the end, this should give you the largest product possible.

(I think I have taken all the possibilities, but if I haven't, please tell me).

6
On

Here is one way to do it:

x:= a_1 \cdot a_2
for(i = 1; i \le n; i++){
  for(j=i+1 ; j \le n; j++){
    x := max{x, a_i \cdot a_j};
  }
}
return x;