Skip to content

Commit 2785b29

Browse files
committed
Maximum Product Subarray
1 parent 8f06302 commit 2785b29

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

Diff for: DSA Crack Sheet/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
- [Rearrange array in alternating positive & negative items with O(1) extra space](https://www.geeksforgeeks.org/rearrange-array-alternating-positive-negative-items-o1-extra-space/ "view topic") - [Cpp Solution](./solutions/Rearrange%20array%20in%20alternating%20positive%20&%20negative%20items%20with%20O(1)%20extra%20space.cpp)
2424
- [Subarray with 0 sum](https://practice.geeksforgeeks.org/problems/subarray-with-0-sum-1587115621/1# "view question") - [Cpp Solution](./solutions/Subarray%20with%200%20sum.cpp)
2525
- [Factorials of large numbers](https://practice.geeksforgeeks.org/problems/factorials-of-large-numbers/0# "view question") - [Cpp Solution](./solutions/Factorials%20of%20large%20numbers.cpp)
26+
- [Maximum Product Subarray](https://practice.geeksforgeeks.org/problems/maximum-product-subarray3604/1 "view question") - [Cpp Solution](./solutions/Maximum%20Product%20Subarray.cpp)
2627
- []( "view question") - [Cpp Solution](./solutions/.cpp)
2728

2829
<!-- - []( "view question") - [Cpp Solution](./solutions/) -->
+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
Maximum Product Subarray
3+
========================
4+
5+
Given an array Arr that contains N integers (may be positive, negative or zero). Find the product of the maximum product subarray.
6+
7+
Example 1:
8+
Input:
9+
N = 5
10+
Arr[] = {6, -3, -10, 0, 2}
11+
Output: 180
12+
Explanation: Subarray with maximum product
13+
is 6, -3, -10 which gives product as 180.
14+
15+
Example 2:
16+
Input:
17+
N = 6
18+
Arr[] = {2, 3, 4, 5, -1, 0}
19+
Output: 120
20+
Explanation: Subarray with maximum product
21+
is 2, 3, 4, 5 which gives product as 120.
22+
Your Task:
23+
You don't need to read input or print anything. Your task is to complete the function maxProduct() which takes the array of integers arr and n as parameters and returns an integer denoting the answer.
24+
Note: Use 64-bit integer data type to avoid overflow.
25+
26+
Expected Time Complexity: O(N)
27+
Expected Auxiliary Space: O(1)
28+
29+
Constraints:
30+
1 <= N <= 500
31+
-102 <= Arri <= 102
32+
*/
33+
34+
long long maxProduct(int *nums, int n)
35+
{
36+
long long min_here = nums[0], max_here = nums[0], ans = nums[0];
37+
38+
for (int i = 1; i < n; ++i)
39+
{
40+
if (nums[i] < 0)
41+
swap(max_here, min_here);
42+
43+
max_here = max((long long)nums[i], max_here * nums[i]);
44+
min_here = min((long long)nums[i], min_here * nums[i]);
45+
46+
ans = max(ans, max_here);
47+
}
48+
49+
return ans;
50+
}

0 commit comments

Comments
 (0)