1

For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4].

 public class Array {
  public static void main(String args[]){

    int a[]={10,15,1,2,3,4,5,11,12};

    int b=1;
    int c=0;
    for(int i=0;i<a.length-1;i++){

       if(a[i]-a[i+1]==-1){

         b=b+1;
         c=c+1;
         if(b>=c)
       {

       System.out.println(a[i]);

         }
         else{
             b=0;
         } 

    }

}
}
}

But i am getting output as 1 2 3 4 11 whereas the output should be 1 2 3 4 5.

How to get the required output,whats the mistake in a code?

4
  • 2
    Have you considered sorting the array first? Commented Apr 3, 2017 at 17:07
  • you have to sort the array first using the Array class Array.sort(a);or you can create a for loop using bubble algorithm Commented Apr 3, 2017 at 17:09
  • please, format your code. It is painful to read. Commented Apr 3, 2017 at 17:11
  • @davidxxx,edited the code.Hope it is readable.Thanks for suggestion Commented Apr 3, 2017 at 17:19

5 Answers 5

2

You can try this out:

int[] array = {10,15,1,2,3,4,5,11,12};
List<Integer> tempList = new ArrayList<>(); // prepare temp list for later use
List<List<Integer>> arrays = new ArrayList<>(); // used to store the sequences
int lastNum = array[0]; // get the fist number for compasion in loop
tempList.add(lastNum);
for (int i = 1; i < array.length; i++) {
    if (array[i]-1 == lastNum) { // check for sequence (e.g fist num was 12,
      // current number is 13, so 13-1 = 12, 
      // so it has the sequence), then store the number
        tempList.add(array[i]); // store it to the temp list
        lastNum = array[i]; // keep current number for the next
    } else { // if it has not the sequence, start the new sequence
        arrays.add(tempList); // fist store the last sequence
        tempList = new ArrayList() // clear for the next sequence
        lastNum = array[i]; // init the lastNumnber
        tempList.add(lastNum);
    }
}
// now iterate for the longest array
// craete an empty array to store the longest
List<Integer> longestLength = new ArrayList<>();
for (List<Integer> arr : arrays) {
    if (arr.size() > longestLength.size()) {
        // check if the current array hase the longest size than the last one
        // if yes, update the last one
        longestLength = arr;
    }
}
// at the end print the result.
System.out.println("longestLength = " + longestLength);

The Result:

longestLength = [1, 2, 3, 4, 5]
Sign up to request clarification or add additional context in comments.

8 Comments

actually i am not getting your logic
@SainathPawar now the logic may be clear for you! check it!
Wrong answer. You dont have to sort the array, subsequence are found in unsorted array
@SainathPawar Try to run it on {4,3,6,5,1,9,6}
"here the sort condition optional". No the sort produces a wrong result according to the OP question.
|
1

Try this code

public class Array {
      public static void main(String args[]){

        int a[]={10,15,1,2,3,4,5,11,12};

        int ms=0;                  // starting point of max subseq
        int me=0;                   //ending point of max subseq
        int cs=0,ce=0;              //starting and ending  point of current subseq
        int max=0,c=0;           // length of max and current subseq
        for(int i=0;i<a.length-1;i++){

           if(a[i]-a[i+1]==-1){

             if(c==0)             //we found the first element of a subseq
             {
               cs=i;ce=i+1;c=2;   //made the starting of currrent seq=i, end=i+1 and length=2
              }
             else             // element is a part of subsequence but not first elem
              {
               ce=i+1;c++;     // increased current ending point
              } 

              if(c>max)          // if lenth of current subseq is now largest then update staring and ending points of max
               {
                   max=c;
                   ms=cs;
                   me=ce;
               }
             }
             else             // subseq ended
             {
             cs=0;
             ce=0;
             c=0;
              }
      }
        for(i=ms;i<=me;i++)           //printing max subsequence
         System.out.println(a[i]);
    }
    }

Note: see comments for description

7 Comments

will you please explain your logic..it would be great help
ya sure, wait a min
,how did you develop this logic,please suggest me some text books or websites to make logic stronger
@SainathPawar you need to practice more.
any text books or website for practising
|
0

Your code should work if you sort the array first. Have you tried that?

2 Comments

its an array not an arraylist
you can still sort it import java.util.array
0
import java.util.*;
    Arrays.sort(a);

then

    if(a[i]+1==a[i+1])
          //print it 
     else
        {
            System.out.print(a[i]);
            i=a.length;
        }//stop the loop

5 Comments

if i use the solution provided by you i am getting output as 1 2 3 4...whereas output needed is 1 2 3 4 5
just add System.out.print(a[i]); in the else statement to include the last i because you ended the loop in the last a[i]+1 will be 6 so it is not equal to 10 then in else include the last sequential integer
that will work only in this case, not in general case
@TanujYadav you can try it in any other primitive int I have edited my answer for clearer info
suppose you have a subsequence of length 3 and then a subsequence of length 6, then you wont print the largest one
0
class Test
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int a[]={10,15,1,2,3,4,5,11,12};
        Arrays.sort(a);
        ArrayList<Integer>output = new ArrayList<Integer>();
        ArrayList<Integer>temp = new ArrayList<Integer>();
        for(int i =1; i<a.length; i++){
            //If elements have difference of one, add them to temp Arraylist
            if(a[i-1] + 1 == a[i]){
                temp.add(a[i-1]);
            }
            else{
                //Add the last consecutive element 
                temp.add(a[i-1]);

                //If temp is lager then output
                if(temp.size() > output.size()){
                    output = (ArrayList<Integer>) temp.clone();
                        temp.clear();
                }           
            }
        }

        //Outside for loop, making sure the output is the longer list. This is to handle the case where the consecutive sequence is towards the end of the array
        if(temp.size() > output.size()){
            output = (ArrayList<Integer>) temp.clone();System.out.println("after clone outside for " + output.toString());
        }   
        System.out.println(output.toString());
    }

}

2 Comments

,it gives o/p as 15 1 2 3 4 5.we require 1 2 3 4 5
I am getting [1, 2, 3, 4, 5] as the output. What is the input you are testing with?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.