《编程之美》183页,问题2.14——求子数组的字数组之和的最大值。(整数数组)

我开始以为可以从数组中随意抽调元素组成子数组,于是就有了一种想法,把最大的元素抽出来,判断是大于0还是小于等于0,如果大于0就对除了这个最大值外剩下的数组部分进行递归:

using System;
using System.Collections.Generic;
using System.Linq;


namespace MaxSumSubArray
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> array = new List<int>() { -1, -2, 1, 2, -1, 1, -3, 6 - 3, -4, 1 };
            List<int> subArray = new List<int>();
            if (array.Max() > 0)
            {
                MaxSumSubArray(array, subArray);
                PrintArray(subArray);
            }
            else
            {
                Console.Write("The max sub-array is {" + array.Max() + "}");
            }
            Console.ReadLine();
        }

        private static void PrintArray(List<int> subArray)
        {
            Console.WriteLine("The max-sum sub-array is:");
            foreach (int num in subArray)
            {
                Console.Write(num);
                Console.Write(" ");
            }
        }

        private static void MaxSumSubArray(List<int> array, List<int> subArray)
        {
            if (array.Max() > 0)
            {
                subArray.Add(array.Max());
                array.Remove(array.Max());
                MaxSumSubArray(array,subArray);
            }
        }
    }
}
View Code

相关文章:

  • 2022-02-03
  • 2021-09-15
  • 2021-06-15
  • 2021-09-21
  • 2021-07-28
  • 2022-01-13
  • 2022-12-23
  • 2021-06-13
猜你喜欢
  • 2021-10-15
  • 2021-09-24
  • 2021-12-18
  • 2021-09-03
  • 2022-01-06
  • 2021-06-29
  • 2021-10-03
相关资源
相似解决方案