求一個已知陣列的最大子陣列和
阿新 • • 發佈:2019-01-09
思路:
用textbox控制元件輸入陣列,再求出最大子陣列和
using System;using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
int maxsum;
string[] strN = textBox1.Text.Split(',');
int[] list = new int[strN.Length];
for (int i = 0; i < strN.Length; i++)
{
list[i] = int.Parse(strN[i]);
}
maxsum = calMaxSumOfArray(list);
textBox2.Text = maxsum.ToString();
}
public int calMaxSumOfArray(int[] a)//獲取最大子陣列和
{
if (null == a)
{
return 0;
}
if (a.Length == 1)
{
return a[0];
}
int sum = a[0];
int temp = a[0];
for (int i = 1; i < a.Length; i++)
{
temp = max(temp + a[i], a[i]);
if (sum < temp)
{
sum = temp;
}
}
return sum;
}
public int max(int a, int b)
{
return a > b ? a : b;
} private void label2_Click(object sender, EventArgs e)
{ }
}
}