-
Notifications
You must be signed in to change notification settings - Fork 0
/
152.maximum-product-subarray.c
133 lines (125 loc) · 3.29 KB
/
152.maximum-product-subarray.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*
* @lc app=leetcode.cn id=152 lang=c
*
* [152] Maximum Product Subarray
*/
// @lc code=start
#include <stdint.h>
#include <stdlib.h>
int maxProduct(int *nums, int numsSize)
{
if (numsSize == 1)
{
return nums[0];
}
int max_product = INT32_MIN, cur_product;
int start, end, negative_pre_product, negative_next_product, negative_size;
negative_size = 0, start = 0, end = 0;
while (1)
{
if (end == numsSize)
{
if (start == end)
{
break;
}
else
{
if (negative_size == 0 || negative_size % 2 == 0 || end - start == 1)
{
if (max_product < cur_product)
{
max_product = cur_product;
}
}
else
{
int removed = cur_product / negative_next_product;
if (removed > max_product)
{
max_product = removed;
}
removed = cur_product / negative_pre_product;
if (removed > max_product)
{
max_product = removed;
}
}
}
break;
}
if (nums[end] == 0)
{
if (start == end)
{
if (max_product < 0)
{
max_product = 0;
}
}
else
{
if (negative_size == 0 || negative_size % 2 == 0 || end - start == 1)
{
if (max_product < cur_product)
{
max_product = cur_product;
}
if (max_product < 0)
{
max_product = 0;
}
}
else
{
int removed = cur_product / negative_next_product;
if (removed > max_product)
{
max_product = removed;
}
removed = cur_product / negative_pre_product;
if (removed > max_product)
{
max_product = removed;
}
}
}
negative_size = 0;
start = end + 1;
end = start;
}
else
{
if (end == start)
{
cur_product = nums[end];
}
else
{
cur_product *= nums[end];
}
if (negative_size == 0)
{
negative_pre_product = cur_product;
}
if (nums[end] > 0 && negative_size > 0)
{
negative_next_product *= nums[end];
}
if (nums[end] < 0)
{
negative_size++;
negative_next_product = nums[end];
}
end++;
}
}
return max_product;
}
// @lc code=end
int main(int argc, char const *argv[])
{
int nums[3] = {-2, 0, -1};
maxProduct(nums, 3);
return 0;
}