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 }

 

转载于:https://www.cnblogs.com/Juntaran/p/5446787.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值