在数组c#列表中查找最大的子数组(降序)

时间:2018-03-06 01:47:38

标签: c# arrays

我需要找到最大的子阵列。例如:数组列表{ 1, 4, 7, 3, -3, -4, -1, 4, 2, 1 }需要找到数字正在减少的最大子数组。

从列表中{ 7, 3, -3, -4 }是一个子阵列和{ 4, 2, 1 },因为前一个是最大的需要打印它。

2 个答案:

答案 0 :(得分:1)

简单

var results = new List<int>();

for (var i = 0; i < input.Length; i++)
{

   // how we check
   var current = new List<int>();

   // just to know if we are are going down
   var lastValue = input[i];

   // second loop make sure we stop if the numbers aren't going down
   for (var j = i; j < input.Length && input[j] <= lastValue; j++)
   {
      current.Add(input[j]);
      lastValue = input[j];
   }
   // Update the result depending on the criteria 
   if (current.Count >= results.Count)
   {
      results = current;
   }
}

// print your awesome numbers
foreach (var value in results)
{
   Console.Write($"{value}, ");
}

You can test it here

答案 1 :(得分:0)

您可以尝试这种LINQ方法:

descending_subarrays.First()

这给出了:

result

然后,您可以使用$("#navbarForm").off('submit').on('submit', function (event) { $("#hiddenField").val('someValue'); });选择查找答案。