本文概述
- C#
- C#
![用于最大总和连续子数组的C#程序](http://img.readke.com/220416/20040C350-0.png)
文章图片
C#
//C# program to print largest
//contiguous array sum
using System;
class GFG {
static int maxSubArraySum( int [] a)
{
int size = a.Length;
int max_so_far = int .MinValue, max_ending_here = 0;
for ( int i = 0;
i <
size;
i++) {
max_ending_here = max_ending_here + a[i];
if (max_so_far <
max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here <
0)
max_ending_here = 0;
}return max_so_far;
}//Driver code
public static void Main()
{
int [] a = { -2, -3, 4, -1, -2, 1, 5, -3 };
Console.Write( "Maximum contiguous sum is " + maxSubArraySum(a));
}
}//This code is contributed by Sam007_
输出如下:
Maximum contiguous sum is 7
如果我们将max_so_far与max_ending_here进行比较, 则仅当max_ending_here大于0时, 才能进一步优化上述程序。
C#
static int maxSubArraySum( int [] a, int size)
{
int max_so_far = 0, max_ending_here = 0;
for ( int i = 0;
i <
size;
i++) {
max_ending_here = max_ending_here + a[i];
if (max_ending_here <
0)
max_ending_here = 0;
/* Do not compare for all
elements. Compare only
when max_ending_here>
0 */
else if (max_so_far <
max_ending_here)
max_so_far = max_ending_here;
}
return max_so_far;
}//This code is contributed
//by ChitraNayal
请参考完整的文章最大总和连续子数组更多细节!
推荐阅读
- C#程序查找出现的奇数次
- C#编程语言入门学习指南提纲
- 不能加硬盘?C盘不够存储卡凑!
- 电脑主板怎样刷bios?
- android studio快捷键大全
- svchost一直在下载怎样处理
- 笔记本触摸板关不掉怎样处理
- 大片不流畅?插帧60fps看电影更畅快!
- 游戏本有没有必要强上电竞屏?