File tree Expand file tree Collapse file tree 2 files changed +45
-0
lines changed
152_maximum_product_subarray Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ all :
2+ gcc -O2 -o test subarray.c
Original file line number Diff line number Diff line change 1+ #include <stdio.h>
2+ #include <stdlib.h>
3+
4+ static int maxProduct (int * nums , int numsSize )
5+ {
6+ if (numsSize == 0 ) {
7+ return 0 ;
8+ }
9+
10+ int i , global_max = nums [0 ], product ;
11+ int local_min = 1 , local_max = 1 ;
12+ 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+ }
29+ }
30+
31+ return global_max ;
32+ }
33+
34+ int main (int argc , char * * argv )
35+ {
36+ int i , count = argc - 1 ;
37+ int * nums = malloc (count * sizeof (int ));
38+ for (i = 0 ; i < count ; i ++ ) {
39+ nums [i ] = atoi (argv [i + 1 ]);
40+ }
41+ printf ("%d\n" , maxProduct (nums , count ));
42+ return 0 ;
43+ }
You can’t perform that action at this time.
0 commit comments