Maximum number of identical digits in a list of arrays

Suppose I have a list of arrays of values ​​{0,1,1,0,1,1,1} Here the maximum repetition of 1 in a contiguous sequence is 3. How to find the maximum score.

 List<String> list = new ArrayList<String>();

for (int i=0;i<5;i++)
{
    System.out.println("Enter value");
    x = in.nextLine();

      list.add(""+x);
}

Map<String, Integer> countMap = new HashMap<>();

for (String word : list) {
    Integer count = countMap.get(word);
    if(count == null) {
        count = 0;
    }
    countMap.put(word, (count.intValue()+1));
}

      

This gives the total of the same values, but I want the maximum continuous values.

+3


source to share


2 answers


public static void main(String args[]) throws IOException{
     List<String> list = new ArrayList<String>();
     List<String> temp = new ArrayList<String>();
     InputStreamReader r=new InputStreamReader(System.in);  
     BufferedReader br=new BufferedReader(r);  


     for (int i=0;i<15;i++)
     {
         System.out.println("Enter value");
         String x=br.readLine();
         list.add(x);
     }

LinkedHashMap<String, Integer> lhm=new LinkedHashMap<String, Integer>();

for(String str1:list){
    int flag=0;
    for(Entry<String, Integer> entry:lhm.entrySet()){   

        if(entry.getKey().equals(str1)){
            flag=1;
            break;
        }}
        if(flag==0){
            lhm.put(str1, 1);
        }


}

int maxCount = 1;
int currCount = 1;
for (int i=1;i<list.size();++i) {
  if (list.get(i).equals(list.get(i-1))) {
    ++currCount;
    if(list.size()==i+1){
        maxCount = Math.max(lhm.get(list.get(i)), currCount); 
      lhm.put(list.get(i), maxCount);
    }
  } else {
      maxCount = Math.max(lhm.get(list.get(i-1)), currCount); 
      lhm.put(list.get(i-1), maxCount);
    currCount = 1;
  }

}


for(Entry<String, Integer> entry:lhm.entrySet()){
    System.out.println("Maximum Sequential occurrence of element- "+entry.getKey()+" is- "+entry.getValue());//display result
}


}

      



The maximum consecutive occurrence of the entire item in the list will be printed above the code.

+1


source


What about:

// Initialize to 1 because first element is equal to itself.
int maxCount = 1;
int currCount = 1;
for (int i=1;i<list.size();++i) {
  if (list.get(i).equals(list.get(i-1))) {
    ++currCount;
  } else {
    currCount = 1;
  }
  maxCount = Math.max(maxCount, currCount);
}
return maxCount;

      



This repeats over your sequence and finds the longest contiguous sequence.

0


source







All Articles