-2

How can i find the longest sub array with a max difference of 0 and 1 with time complexity of O(n) and space of O(1)? Thank you in advance for the feed backs & solutions!

For example: input array is {3, 3, 4, 5, 5, 5, 6, 6, 7, 7, 7, 7, 7} and output should be something like: starting index is 6 with length 7.

Another example: input array is {5, 5, 5, 5, 3, 3, 2, 2, 1} and output: index 0 and length 4.

Possible solution: I'm using nested for loops with var i and var j

  • 5
    This sounds like a homework question. Further, it is not clear what you are asking. What do you mean “max difference of 0 and 1”? – Dúthomhas Sep 27 '17 at 04:15
  • Homework alert? Very simple, iterate over the parent array, and compare the lengths of each sub-array, kind of like a max() implementation. The space O(1) would be a simple variable, and the loop would be your O(n) time complexity. – Rafael Sep 27 '17 at 04:15
  • Welcome to Stack Overflow. This is not a code writing service; you cannot just state what the problem is and expect someone to write code for you. You must show some effort solving the problem yourself by posting code showing your attempt at solving the problem, and where you got stuck. Your “possible solution” suggests you’ve done something; let’s see it. – AJNeufeld Sep 27 '17 at 04:24

1 Answers1

0

You are not allowed to copy this and use it for your assignment, but it should provide you with insight about how to do it.

class Find {
    public static void main(String args[]) {
        int parent[][] = {
            {1,2,3,4},
            {8,7,6,5,8},
            {9,8},
            {8,7,6,5,8,0,0,0,9,9,9},
            {8}
        };

        int max = parent[0].length;
        int i = 0;//CONSTANT SPACE O(1)
        //LINEAR TIME O(n)
        for (int j = 1; j < parent.length; j++) {
            if (parent[j].length > max) {
                max = parent[j].length;
                i = j;
            }
        }

        System.out.println("Longest sub-array index: " + i);
    }
}

I can feed you for today, but you need to learn this stuff and feed yourself for a lifetime...

Rafael
  • 7,605
  • 13
  • 31
  • 46