Maximum Product of Two Elements in an Array

LeetCode # 1464

LOGIC

Time Taken = 37 mins

  • We have keep track of 2 number BIG NUMBER and SMALL NUMBER while iterating array from 2 to length-1.
  • Rest of the code is simple.
  • Most of the confusion occurs while initializing the index corresponding to
    • bigNumberIndex and smallNumberIndex
    • else condition was wrong at the beginning
      • i.e. (nums[bigNumberIndex] > nums[i] ) which is going to be always true if we enter in else condition.
      • Keep it simple, don’t write clever code.

JAVA CODE Maximum Product of Two Elements in an Array

class Solution {
    public int maxProduct(int[] nums) {
        if (nums.length == 2){
            return ((nums[0]-1) * (nums[1]-1));
        }

        int smallNumberIndex = 0, bigNumberIndex = 1;
        if (nums[0] > nums[1]){
            bigNumberIndex = 0;
            smallNumberIndex = 1;
        }

        for (int i = 2; i < nums.length; i++){
            if (nums[i] > nums[bigNumberIndex]){
                smallNumberIndex = bigNumberIndex;
                bigNumberIndex = i;
            } else if (nums[i] > nums[smallNumberIndex]) {
                smallNumberIndex = i;
            }
        }
        return ((nums[bigNumberIndex]-1) * (nums[smallNumberIndex]-1));
    }
}

Visit https: https://codeandalgo.com for more such contents

Leave a Reply

Your email address will not be published. Required fields are marked *