请教一个算法!
一个数组,如:A=(0 0 0 0 0 3.5 4.7 0 0 0 8 0 9.0 4.5 6.5 9)要求:
求出A中所有连续不为0的片段中,每一个数据和片段最大值的乘积,然后求该数组中上述乘积之和。
比如上式,应该求出如下值:
(3.5+4.7)*max(3.5,4.7) +8*8+(9.0+4.5+6.5+9)*max(9.0, 4.5, 6.5,9)
这个算法该如何实现? 可能很简单,但我在写条件语句while或if时,总跳入死循环。
请教高手。多谢。 --------------------编程问答--------------------
int[] array={0,0,0,0,0,3.5,4.7,0,0,0,8,0,9.0,4.5,6.5,9};--------------------编程问答--------------------
int maxValue=0,sum=0,result=0;
foreach(int n in array)
{
if(n==0)
{
result+=sum*maxValue;
maxValue=0;
sum=0;
}
else
{
sum+=n;
if(n>maxValue) maxValue=n;
}
}
result+=sum*maxValue;
double [] db={0 ,1 ,2 ,3 };
double sum = 0.0;
double sumAll = 0.0;
double max = 0.0;
for (int i = 0; i < db.Length; i++)
{
if (db[i] != 0)
{
sum = sum + db[i];
if (db[i] > max)
{
max = db[i];
}
if (i == db.Length - 1 || db[i + 1] == 0)
{
sum = max * sum;
}
}
else
{
sumAll = sumAll + sum;
sum = 0;
}
}
sumAll 就是结果 --------------------编程问答--------------------
搞错了,要用double,随手写的,没留意--------------------编程问答--------------------
double[] array={0,0,0,0,0,3.5,4.7,0,0,0,8,0,9.0,4.5,6.5,9};
double maxValue=0,sum=0,result=0;
foreach(int n in array)
{
if(n==0)
{
result+=sum*maxValue;
maxValue=0;
sum=0;
}
else
{
sum+=n;
if(n>maxValue) maxValue=n;
}
}
result+=sum*maxValue;
foreach(int n in array)
也改成:foreach(double n in array)
--------------------编程问答-------------------- Double [] A={0, 0, 0, 0, 0, 3.5, 4.7, 0, 0, 0, 8, 0, 9.0, 4.5, 6.5, 9};
Double total = 0;
Double part = 0;
Double max = 0;
for (int i = 0; i < A.Length; i++)
{
if (A[i] == 0)
{
total += part * max;
part = 0;
max=0;
Response.Write(total+"<br>");
}
else
{
if(A[i]>max)
max = A[i];
part += A[i];
}
}
if(part>0)
total += part * max; --------------------编程问答-------------------- xiexie
补充:.NET技术 , C#