Find the Maximum Product of Two Elements in an Array

Find the Maximum Product of Two Elements in an Array

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).

LeetCode Problem: Link | Click Here

class Solution {
    public int maxProduct(int[] nums) {
        // Initialize variables
        int startVal = (nums[0] - 1) * (nums[1] - 1); // Calculate product of first two elements minus 1
        int len = nums.length; // Get the length of the array
        int finalVal = 0; // Initialize variable to store the final maximum product
        int preFinal = 0; // Temporary variable to store intermediate products

        // Check if array length is greater than 2
        if (len > 2) {
            // Loop through the array elements for product calculation
            for (int i = 0; i < len - 1; i++) {
                for (int j = i + 1; j < len; j++) {
                    preFinal = (nums[i] - 1) * (nums[j] - 1); // Calculate product of selected elements minus 1
                    if (preFinal > finalVal) {
                        finalVal = preFinal; // Update finalVal if preFinal is greater
                    }
                }
            }
            return finalVal; // Return the maximum product
        } else {
            return startVal; // If array length is less than or equal to 2, return startVal
        }
    }
}