34. Top Two Product
A game awards bonus points by multiplying the values on two different cards drawn from a hand. The cards can carry negative values, and the player wants the largest possible product.
Write a method maxPairProduct that takes the array nums of card values and returns the largest product you can get by multiplying the values at two different positions. Note that two negative values multiply to a positive result.
Example 1
- Input:
- nums = [3,4,5,2]
- Output:
- 20
- Explanation:
The two largest cards are 4 and 5, giving 20.
Example 2
- Input:
- nums = [-10,-9,5,6]
- Output:
- 90
- Explanation:
Two negative cards multiply to a positive: -10 x -9 = 90, which beats 5 x 6 = 30.
Constraints
2 ≤ nums.length ≤ 1000
-104 ≤ nums[i] ≤ 104
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n log n)
- Space
- O(n)