Maximum Subsequence Multiplication

最大连续乘积算法
本文介绍了一种求解整数数组中最大连续乘积的算法。通过维护当前最大正乘积和最小负乘积,该算法能高效地找出数组中最大的连续乘积。

Given an array a contains integers, return
the maximum consecutive multiplication
Example:
int[] a = {2, -2, -3, 4, -5, 6} ;
return 360 (-3 * 4 * -5 * 6)

code

ContractedBlock.gifExpandedBlockStart.gifCode
 1 // Use two variable max and min to record the max positive multiplication
 2 // and min negetive multiplication at current position
 3 public long Multiplication(long[] a)
 4 {
 5     long max = 1// max positive multiplication at current position
 6     long min = 1// min negetive multiplication at current position
 7     long r = 1;   // result, max multiplication totally
 8 
 9     for (int i = 0; i < a.Length; i++)
10     {
11         if (a[i] > 0)
12         {
13             max *= a[i];
14             min = Math.Min(min * a[i], 1);
15         }
16         else if (a[i] == 0)
17         {
18             max = 1;
19             min = 1;
20         }
21         else // i < 0
22         {
23             long temp = max;
24             max = Math.Max(min * a[i], 1);
25             min = temp * a[i];
26         }
27         r = Math.Max(r, max);
28     }
29     return r;
30 }
31 

 

转载于:https://www.cnblogs.com/graphics/archive/2009/06/10/1500570.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值