Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 71062d7

Browse files
ADD Maximum-Product-Subarray problem #63
1 parent 69eb622 commit 71062d7

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

‎Medium/maximum-product-subarray.cs

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
5+
public class Solution
6+
{
7+
#region Approach 1 (Brute Force)
8+
private static int _GetMaxProductOfArray(IEnumerable<int> nums)
9+
{
10+
if (nums == null || nums.Count() == 0)
11+
{
12+
return 0;
13+
}
14+
15+
if (nums.Count() == 1)
16+
{
17+
return nums.FirstOrDefault();
18+
}
19+
20+
//int maxProduct = 1;
21+
//foreach (int num in nums)
22+
//{
23+
// maxProduct *= num;
24+
//}
25+
26+
return nums.Aggregate(1, (acc, x) => acc * x);
27+
}
28+
public static int MaxProduct(int[] nums)
29+
{
30+
if (nums == null || nums.Length == 0)
31+
{
32+
return 0;
33+
}
34+
35+
if (nums.Length == 1)
36+
{
37+
return nums[0];
38+
}
39+
40+
int maxProduct = int.MinValue;
41+
for (int i = 0; i < nums.Length; i++)
42+
{
43+
for (int j = i; j <= nums.Length; j++)
44+
{
45+
maxProduct = Math.Max(maxProduct, _GetMaxProductOfArray(nums.Skip(i).Take(j - i)));
46+
}
47+
}
48+
49+
return maxProduct;
50+
}
51+
#endregion
52+
53+
#region Approach 2 (Dynamic Programming)
54+
public static int MaxProduct2(int[] nums)
55+
{
56+
if (nums == null || nums.Length == 0)
57+
{
58+
return 0;
59+
}
60+
61+
if (nums.Length == 1)
62+
{
63+
return nums[0];
64+
}
65+
66+
(int currMax, int currMin) = (1, 1);
67+
int maxProduct = nums.Max();
68+
69+
foreach (int num in nums)
70+
{
71+
int tempMax = currMax;
72+
73+
currMax = Math.Max(Math.Max(currMax * num, currMin * num), num);
74+
currMin = Math.Min(Math.Min(tempMax * num, currMin * num), num);
75+
76+
maxProduct = Math.Max(maxProduct, currMax);
77+
}
78+
79+
return maxProduct;
80+
}
81+
#endregion
82+
83+
public static void Main(string[] args)
84+
{
85+
int[] nums = { 2, -3, -2, 4 };
86+
87+
Console.WriteLine(MaxProduct(nums));
88+
Console.WriteLine(MaxProduct2(nums));
89+
90+
Console.ReadKey();
91+
}
92+
}
93+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /