|
| 1 | +#include <limits.h> |
1 | 2 | #include <stdio.h>
|
2 | 3 | #include <stdlib.h>
|
3 | 4 |
|
4 |
| -static int maxProduct(int* nums, int numsSize) |
| 5 | +static inline int min(int a, int b) |
5 | 6 | {
|
6 |
| - if (numsSize == 0) { |
7 |
| - return 0; |
8 |
| - } |
| 7 | + return a < b ? a : b; |
| 8 | +} |
| 9 | + |
| 10 | +static inline int max(int a, int b) |
| 11 | +{ |
| 12 | + return a > b ? a : b; |
| 13 | +} |
9 | 14 |
|
10 |
| - int i, global_max = nums[0], product; |
11 |
| - int local_min = 1, local_max = 1; |
| 15 | +static int maxProduct(int* nums, int numsSize) |
| 16 | +{ |
| 17 | + int i, maximum = INT_MIN; |
| 18 | + int dp_min = 1; |
| 19 | + int dp_max = 1; |
| 20 | + /* dp records the min or max result of subarray nums[0...i] */ |
12 | 21 | for (i = 0; i < numsSize; i++) {
|
13 |
| - if (nums[i] > 0) { |
14 |
| - product = local_max * nums[i]; |
15 |
| - global_max = product > global_max ? product : global_max; |
16 |
| - local_max *= nums[i]; |
17 |
| - local_min *= nums[i]; |
18 |
| - } else if (nums[i] < 0) { |
19 |
| - product = local_min * nums[i]; |
20 |
| - global_max = product > global_max ? product : global_max; |
21 |
| - int tmp = local_max; |
22 |
| - local_max = product > 1 ? product : 1; |
23 |
| - local_min = tmp * nums[i]; |
24 |
| - } else { |
25 |
| - global_max = global_max > 0 ? global_max : 0; |
26 |
| - local_max = 1; |
27 |
| - local_min = 1; |
28 |
| - } |
| 22 | + int prev_min = dp_min; |
| 23 | + int prev_max = dp_max; |
| 24 | + dp_min = min(nums[i], min(prev_min * nums[i], prev_max * nums[i])); |
| 25 | + dp_max = max(nums[i], max(prev_min * nums[i], prev_max * nums[i])); |
| 26 | + maximum = max(dp_max, maximum); |
29 | 27 | }
|
30 | 28 |
|
31 |
| - return global_max; |
| 29 | + return maximum; |
32 | 30 | }
|
33 | 31 |
|
34 | 32 | int main(int argc, char **argv)
|
35 | 33 | {
|
| 34 | + |
| 35 | + |
36 | 36 | int i, count = argc - 1;
|
37 | 37 | int *nums = malloc(count * sizeof(int));
|
38 | 38 | for (i = 0; i < count; i++) {
|
|
0 commit comments