Intuition¶
Since all values are positive, (a-1)*(b-1) is maximized by choosing the two
largest numbers in the array. Track those two values in one pass, then return
(first - 1) * (second - 1).
Approach: Track Top Two Values¶
- Initialize
firstMaxandsecondMaxto 0. - For each
numinnums: - If
num > firstMax, shiftfirstMaxintosecondMaxand updatefirstMax. - Else if
num > secondMax, updatesecondMax. - Return
(firstMax - 1) * (secondMax - 1).
Complexity¶
- Time complexity: $$O(n)$$, where
nisnums.length. - Space complexity: $$O(1)$$.
Code¶
Go¶
func maxProduct(nums []int) int {
firstMax, secondMax := 0, 0
for _, num := range nums {
if num > firstMax {
secondMax, firstMax = firstMax, num
} else if num > secondMax {
secondMax = num
}
}
return (firstMax - 1) * (secondMax - 1)
}