昨天晚上花了几个小时,终于把这个题目给实现了。后面再优化。今天先贴出来晒晒。
据说是浙江大学计算机系一道考研题目(给定一个有符号整形数组,输出和胃最大并且连续的子数组)。当初只会算最大值,不会返回一个数组作为结果。花了点时间,把程序改进了一下。有些不成熟。先放放。好歹是实现了。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SumMax { class Program { public int[] Sum_Max(int[] array) { int sum = 0; int max = array[0]; int i = 0; int index_start = i; int index_end = i; int index_temp = 0; for (i = 0; i < array.Length;i++ ) { if (sum >= 0)///Sum if the result >= 0. { sum += array[i]; } else ///A new sum if the result of sum < 0 and a new start for the new array { sum = array[i]; index_temp = i; } if (sum > max) ///Compare the max and result of sum and set the index end if sum > max { max = sum; index_end = i; } if (index_temp <= index_end) ///if Temp < end, start should be changed { index_start = index_temp; } } /// create the result to be a new array int[] result = new int [index_end - index_start + 1]; for (int index = 0; index < result.Length; index++) { result[index] = array[index_start++]; } return result; } static void Main(string[] args) { int[] array = { 2, 3, -6, 10, 50, 80, -100, -200, 50}; /// a test case Program p = new Program(); int[] resultArray = p.Sum_Max(array); int sum = 0; foreach (int a in resultArray) { sum += a; Console.Write(a + ", "); } Console.WriteLine(); Console.Write(sum); Console.ReadLine(); } } }
一道数组求连续子集最大值的题目。,布布扣,bubuko.com
原文:http://www.cnblogs.com/simontaylor/p/3725363.html