例如,我们有一个像
{9,8,7,9,5,4,10,3,12}
现在递减序列是
9,8,7 => 9+8+7 = 24
9,5,4 => 9+5+4 = 18
10,3 => 10+3 =13
12 => 12
在上面的总和中,24 是最高的,我们必须打印该值作为结果。
不应使用数组列表等内置函数
需要动态答案并且答案必须满足该类型的所有其他数组
我使用的代码是
int[] arr2 = new int[8] { 10, 9, 8, 9, 7, 6, 11, 5 };
int temp2 = 0;
for (int i = 1; i <= arr2.Length - 1; i++)
{
for (int j = i - 1; j <= arr2.Length - 1; j++)
{
if (arr2[j] > arr2[i])
{
temp2 = temp2 + arr2[i]+arr2[j];
}
}
}
基本,未优化:
int[] arr = { 9, 8, 7, 9, 5, 4, 10, 3, 12 };
int maxSum = 0;
int curSum = 0;
for(int i = 0; i < arr.Length; i++)
{
// new sequence
if(curSum == 0)
{
curSum = arr[i];
}
// seqence decreasing
else if(arr[i] <= arr[i - 1])
{
curSum += arr[i];
}
// end of sequence
else
{
// check if the sequence produced a greater sum
if(maxSum < curSum)
{
maxSum = curSum;
}
Console.WriteLine(curSum);
curSum = arr[i];
}
}
Console.WriteLine(curSum);
// final check
if(curSum > maxSum)
{
maxSum = curSum;
}
Console.WriteLine($"Max: {maxSum}");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句