题目
给你一个整数数组 nums,请你选择数组的两个不同下标 i 和 j,使 (nums[i]-1)*(nums[j]-1) 取得最大值。
请你计算并返回该式的最大值。
代码
方法一:排序
public int maxProduct(int[] nums) {
Arrays.sort(nums);
int max = (nums[nums.length - 1] - 1) * (nums[nums.length - 2] - 1);
return max;
}
方法二:使用变量记录
1、使用两个变量,一个存放最大值(默认为nums[0]),一个存放次大值(默认为0)
2、从下标为1处开始遍历nums数组,一次进行最大值和次大值的赋值。
public int maxProduct2(int[] nums) {
int max1 = nums[0];
int max2 = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > max1) {
max2 = max1;
max1 = nums[i];
} else if (nums[i] > max2) {
max2 = nums[i];
}
}
return (max1 - 1) * (max2 - 1);
}
反思
做完一道题,要想想还有没有更好的方法解决。
end.