我已經評論了我的邏輯是什麼。它應該工作的方式是,例如,如果我們有K=3
和S={1,7,2,4}
,那麼每個對的總和不分的最大子集K
是{1,7,4}
。我的算法的缺陷在哪裏找到每個對的和不分K的最大子集?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
int k = Int32.Parse(Console.ReadLine().Split(' ')[1]);
var S = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
// first get all pairs in S whose sum doesn't divide k,
// each pair in their own subset set of S
var subsets = from i in S
from j in S
where i < j && ((i + j) % k != 0)
select new HashSet<int>() { i, j };
// for each subset, for each number in the original set
// not already in the subset, if the number summed with
// every numer in the subset doesn't divide k, add the
// number to the subset
foreach(var ss in subsets)
foreach(int n in S.Where(q => !ss.Contains(q)))
if(ss.All(m => (m + n) % k != 0))
ss.Add(n);
// get the size of the largest subset, print to console
int max = subsets.Select(ss => ss.Count).Max();
Console.WriteLine(max);
}
}
你能給出一個失敗的輸入嗎? – yossico
我的示例中的一個失敗。這個例子是從https://www.hackerrank.com/challenges/non-divisible-subset?h_r=next-challenge&h_v=zen – user6048670
我想知道你會發布多少個問題,直到意識到LINQ查詢必須實現進入一些內存集合,以防它們被多次使用。 '子集。選擇(..'只是創建新的'HastSet's,因此拋出了你在前一個循環中做的所有事情。 –