Skip to main content
2 of 2
added 35 characters in body; Post Made Community Wiki
chux
  • 33.7k
  • 2
  • 38
  • 92

Hmm, apparently OP has done this - although the problem statement did not suggest it.


Is there a way to implement it without a temporary sorted array?

Yes - at least not a sorted array of size n, but of size 3.

A single pass through the list only needs to keep track of the 3 largest prior values. So we still have a sorted array of 3.

// Pseudo code
Fill max_list[3] with sorted first 3 array elements.
product = max_list[0] * max_list[1] * max_list[2]
for (i = 3; i < n; i++) {
  if (list[i] > max_list[0]) {
    max_list[0] = list[i]
    sort_list low to high // Perhaps bubble sort here.
    form product
  }
  output product to expected array
}


  

Complexity: O(n).


OP mentions value are non-negative. Even with negatives only short lists are needed.

chux
  • 33.7k
  • 2
  • 38
  • 92