一道数组求连续子集最大值的题目。

昨天晚上花了几个小时,终于把这个题目给实现了。后面再优化。今天先贴出来晒晒。

 

据说是浙江大学计算机系一道考研题目(给定一个有符号整形数组,输出和胃最大并且连续的子数组)。当初只会算最大值,不会返回一个数组作为结果。花了点时间,把程序改进了一下。有些不成熟。先放放。好歹是实现了。

 

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();
        }
    }
}

 

转载于:https://www.cnblogs.com/simontaylor/p/3725363.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值