Given an integer array nums, please choose two different subscripts i and j of the array so that (nums[i]-1)*(nums[j]-1) gets the maximum value.
Please calculate and return the maximum value of this formula.
Traverse to find the maximum and sub-maximum values in the array:
class Solution {
public:
int maxProduct(vector<int>& nums) {
int i = 0, j = 0;
for (int num : nums) {
if (num > i) {
j = i; // 当前最大值变为次最大值
i = num;
} else if (num > j) {
j = num;
}
}
return (i - 1) * (j - 1);
}
};