Sponsored
Sponsored
One effective way to find the maximum product is by first sorting the array, then selecting the two largest elements, which will naturally be at the end of the sorted list. The product of their decremented values will provide the result.
Time Complexity: O(n^2) due to the bubble sort implementation. Space Complexity: O(1) since no extra space is used.
1using System;
2
3public class Solution {
4 public int MaxProduct(int[] nums) {
5 Array.Sort(nums);
6 int n = nums.Length;
7 return (nums[n - 1] - 1) * (nums[n - 2] - 1);
8 }
9 public static void Main() {
10 Solution sol = new Solution();
11 int[] nums = {3, 4, 5, 2};
12 Console.WriteLine(sol.MaxProduct(nums));
13 }
14}
The C# solution applies Array.Sort()
to sort the nums array. Post sorting, it reduces the last two numbers by one and calculates their product.
This approach finds the two largest numbers in a single pass without sorting. By iterating over the array, we track the largest and second-largest numbers. With these two numbers, we compute the maximum product efficiently.
Time Complexity: O(n) because we pass through the array just once. Space Complexity: O(1) as no additional space is required.
1
The JavaScript code efficiently computes the maximum product in a single loop, updating two max variables as appropriate all the way to the end of the list.