一道数组求连续子集最大值的题目。
生活随笔
收集整理的這篇文章主要介紹了
一道数组求连续子集最大值的题目。
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
昨天晚上花了幾個小時,終于把這個題目給實現了。后面再優化。今天先貼出來曬曬。
?
據說是浙江大學計算機系一道考研題目(給定一個有符號整形數組,輸出和胃最大并且連續的子數組)。當初只會算最大值,不會返回一個數組作為結果。花了點時間,把程序改進了一下。有些不成熟。先放放。好歹是實現了。
?
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 arrayint[] 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();}} }?
轉載于:https://www.cnblogs.com/simontaylor/p/3725363.html
總結
以上是生活随笔為你收集整理的一道数组求连续子集最大值的题目。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASIHTTP 框架,同步、 异步请求
- 下一篇: python进阶八_警告和异常