LeetCode 152

Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number)
which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

 

 1 /*************************************************************************
 2     > File Name: LeetCode152.c
 3     > Author: Juntaran
 4     > Mail: Jacinthmail@gmail.com
 5     > Created Time: Fri 29 Apr 2016 03:46:31 PM CST
 6  ************************************************************************/
 7 
 8 /*************************************************************************
 9 Maximum Product Subarray
10 
11 Find the contiguous subarray within an array (containing at least one number)
12 which has the largest product.
13 
14 For example, given the array [2,3,-2,4],
15 the contiguous subarray [2,3] has the largest product = 6.
16 ************************************************************************/
17 
18 #include<stdio.h>
19 
20 void maxAndmin( int a, int b, int c, int* max, int* min )
21 {
22     if( a > b )
23     {
24         if( a > c )
25         {
26             *max = a;
27             *min = b > c ? c : b;
28         }
29         else
30         {
31             *max = c;
32             *min = b;
33         }
34     }
35     else
36     {
37         if( a > c )
38         {
39             *max = b;
40             *min = c;
41         }
42         else
43         {
44             *max = b > c ? b : c;
45             *min = a;
46         }
47     }
48 }
49 
50 int maxProduct( int* nums, int numsSize )
51 {
52     int result = nums[0];
53     int lastMax = nums[0];
54     int lastMin = nums[0];
55     int i;
56     for( i=1; i<numsSize; i++ )
57     {
58         maxAndmin( nums[i], nums[i]*lastMax, nums[i]*lastMin, &lastMax, &lastMin );
59         result = lastMax > result ? lastMax : result;
60     }
61     printf("result is %d\n", result);
62     return result;
63 }
64 
65 int main()
66 {
67     int nums[] = {-2, 3, -4};
68     int numsSize = 3;
69     maxProduct( nums, numsSize );
70     return 0;
71 }

 

posted @ 2016-04-29 16:36  Juntaran  阅读(153)  评论(0编辑  收藏  举报