using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
/*
*
* Problem 3:
* Complete a function to find the sub array of an integer array with
* largest sum. For example, for the array [1, -2, 3, 10, -4, 7, 2, -5],
* you should find 3 + 10 + (-4) + 7 + 2 = 18. It is best to write the
* code in C#.
*
*/
class Program
{
static void Main(string[] args)
{
List<int> test1 = new List<int>()
{
1, -2, 3, 10, -4, 7, 2, -5
};
List<int> test2 = new List<int>()
{
1, 5 , 11, -21, 7 , 3 ,6, 9, -15
};
List<int> result1 = MaxSumArray(test1);
List<int> result2 = MaxSumArray(test2);
System.Console.WriteLine(string.Join(" ", result1.ToArray()));
System.Console.WriteLine(string.Join(" ", result2.ToArray()));
System.Console.ReadLine();
}
/*
* When we add a positive number, the sum will increase;
* When we add a negative number, the sum will decrease.
* If the sum currently obtained is a negative number,
* then this sum should be discarded and reset in the subsequent accumulation.
*/
static List<int> MaxSumArray(List<int> input)
{
List<int> ret = new List<int>();
/// Find out the continuous sub array of input that has maximum summation.
/// Required to be O(n)
///
if (input == null)
{
return ret;
}
int curSum = 0, maxSum = 0;
/// Initializing the maximum and end index
int curSumIndexStart = 0;
int maxSumIndexStart = 0, maxSumIndexEnd = 0;
int i = 0, len = input.Count;
maxSum = input[0];
for (i = 0; i < len; i++)
{
// the maximum value of the "index_start"
curSum += input[i];
if (curSum > maxSum)
{
// The current sum is greater than the largest.
// Update the largest.
// Record the index.
maxSum = curSum;
maxSumIndexStart = curSumIndexStart;
maxSumIndexEnd = i;
}
if (curSum < 0)
{
// The current sum is less than 0,
// Set curSum to 0.
// Set index_start
curSum = 0;
curSumIndexStart = i + 1;
}
}
ret = input.GetRange(maxSumIndexStart, maxSumIndexEnd + 1 - maxSumIndexStart);
return ret;
}
}
}
求和最大的数字子串
最新推荐文章于 2018-09-06 23:10:00 发布