Description
Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).
Example 1:
1 | Input: nums = [3,4,5,2] |
Example 2:
1 | Input: nums = [1,5,4,5] |
Example 3:
1 | Input: nums = [3,7] |
Constraints:
1 | 2 <= nums.length <= 500 |
Solutions
Sorting
- Sort first
- then the last two values are the largest two values
- find the final answer as required and return
1 | # O(nlogn) time | O(1) space |
Two Pointers
This problem is actually to find the first and second largest numbers in the array. We only need to use first and second to represent the subscripts of the first and second largest numbers, and then traverse the array and compare them one by one.
1 | # O(n) time | O(1) space |