解法一

数据范围显示数组元素全是正数,所以直接找最大的两个数。
一开始记录了前两大数的下标,默认为0,从1开始比,没有考虑第0个数最大的情况,不够仔细。

  1. class Solution {
  2. public int maxProduct(int[] nums) {
  3. int max1 = -1;
  4. int max2 = -1;
  5. for (int i = 0; i < nums.length; ++i) {
  6. if (nums[i] > max1) {
  7. max2 = max1;
  8. max1 = nums[i];
  9. } else if (nums[i] > max2) {
  10. max2 = nums[i];
  11. }
  12. }
  13. return ((max1 - 1) * (max2 - 1));
  14. }
  15. }