例如中最大的子數組的大小,考慮到陣列A={1,3,2,17,10}
,答案是3
因爲集合{1,2,3}
是最大的集合,使得一些a
在集合中,集合中的每個元素都是範圍[a, a + 4]
(即a+4
)。哪裏是我的算法缺陷與每個元素找到DISTA
我的算法是像
int[] toys = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
Array.Sort(toys);
int max_together = 0;
for(int i = 0; i < toys.Length; ++i)
{
int plus_four = toys[i] + 4;
int j = i + 1;
for(; j < toys.Length && toys[j] <= plus_four; ++j);
int span = j - i;
if(span > max_together)
{
max_together = span;
}
}
和它的失敗大部分的測試案例。
或者,也許我讀https://www.hackerrank.com/challenges/priyanka-and-toys?h_r=next-challenge&h_v=zen錯誤......
我的完整的解決方案是
using System;
using System.Collections.Generic;
using System.IO;
class Solution
{
static void Main(String[] args)
{
Console.ReadLine(); // N
int[] toys = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
Array.Sort(toys);
int max_together = 0;
for(int i = 0; i < toys.Length; ++i)
{
int plus_four = toys[i] + 4;
int j = i + 1;
for(; j < toys.Length && toys[j] <= plus_four; ++j);
int span = j - i;
if(span > max_together)
{
max_together = span;
}
}
Console.WriteLine(1 + (toys.Length - max_together));
}
}