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.
1#include <vector>
2#include <algorithm>
3#include <iostream>
4
5int maxProduct(std::vector<int>& nums) {
6 std::sort(nums.begin(), nums.end());
7 int n = nums.size();
8 return (nums[n-1] - 1) * (nums[n-2] - 1);
9}
10
11int main() {
12 std::vector<int> nums = {3, 4, 5, 2};
13 std::cout << maxProduct(nums) << std::endl;
14 return 0;
15}
The C++ implementation utilizes the STL sort
function to sort the array. After sorting, it takes the last two elements and calculates the product of their decremented values for the result.
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 C implementation maintains two variables to track the largest and second-largest numbers encountered. Each element is compared in sequence, and the variables are adjusted appropriately to find these numbers without sorting the full array.