2016-08-16 20 views
-4

例如中最大的子數組的大小,考慮到陣列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)); 
    } 
} 

回答

0

在快看,我發現你正在努力尋找有序陣列上最大跨度(即1, 2,3,10,17),而測試用例則希望您在排序前的給定數組(即1,3,2,17,10)上找到最大跨度。

0

如果您購買1件重量爲w1的玩具,您可以免費獲得重量介於[w1,w1 + 4]之間的所有玩具。該問題要求您找到需要購買的玩具的最小數量,以便在輸入中獲得所有玩具。在這個例子中A = {1,3,2,17,10},答案是3,因爲需要購買玩具1(或2或3),17和10

Java代碼

int num[] = {1,3,2,17,10}; 
Arrays.sort(num); 
     int result=1; 
     int lastToy=num[0]; 
     for(int i=1;i<n;i++) 
      { 
      if(num[i] > lastToy+4) 
       { 
       result++; 
       lastToy= num[i]; 
      } 
     } 
相關問題