求环形数组的最大子数组和
设计思想:
新建一个两倍长的数组,并将两个输入的已知数组连接起来赋值给它
进行n次遍历,将数组拆成n个一维数组,则这n个数组为原环形数组遍历的n个子数组情况
再分别对其求最大子数组和
日志:
代码:
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 求循环数组最大子数组和 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { 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]); } dataGridView1.RowCount = list.Length; int[] temp = new int[2*list.Length]; int[] zilist=new int [list.Length]; for(int i = 0; i < list.Length;i++) { temp [i]=list[i]; temp [i+list.Length]=list[i]; } for (int i = 0; i < list.Length;i++ ) { string ziList="";; string minlist = ""; int maxsum = list[0]; for (int j = 0; j < list.Length; j++) { zilist[j] = temp[i + j]; ziList += (Convert.ToString(zilist[j]) + ","); } dataGridView1.Rows[i].Cells[0].Value = ziList; maxsum = MaxListSum(zilist); int n = Convert.ToInt32(label1.Text); int m = Convert.ToInt32(label2.Text); for (int j = n; j < m + 1; j++) { minlist += (Convert.ToString(zilist[j]) + ","); } dataGridView1.Rows[i].Cells[1].Value = minlist; dataGridView1.Rows[i].Cells[2].Value=Convert.ToString(maxsum); } } public int MaxListSum(int[] a)//获取最大子数组和 { int m = 0; int n = 0; 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++) { if (a[i] < (temp + a[i])) { temp = temp + a[i]; } else { temp = a[i]; } if (sum < temp) { n = m; m = i; label1.Text=(Convert.ToString(n)); label2.Text = (Convert.ToString(m)); sum = temp; } } return sum; } private void label2_Click(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { Application.Exit(); } private void label3_Click(object sender, EventArgs e) { } } }
结果截图: