Find max length of elements from an array












3















I am working on a program where I need to find out the maximum chain that can be formed from a given array.



Example:



Let's say input is :



Arr[0] = 5
Arr[1] = 4
Arr[2] = 0
Arr[3] = 3
Arr[4] = 1
Arr[5] = 6
Arr[6] = 2


Now if I take the array index and the corresponding value the possible max chain I can form is



index 0 with value 5 --> index 5 with value 6 --> index 6 with value 2 --> index 2 with value 0. This cycle repeats so this is my maximum chain i can form using this array



Here is my code:



public static int getMax(int nums) {
int result = 0;
for (int i = 0; i < nums.length; i++) {
List<Integer> list = new ArrayList<>();
list.add(i);
int temp = i;
while (true) {
int next = nums[temp];
if (list.contains(next)) {
break;
} else {
list.add(next);
temp = next;
}
}
result = Math.max(result, list.size());
}
return result;
}


I have come up with above logic but I see that in my code I am trying to find multiple chains of the same type.



It means if I print my list it has these values:



[0, 5, 6, 2]
[1, 4]
[2, 0, 5, 6]
[3]
[4, 1]
[5, 6, 2, 0]
[6, 2, 0, 5]


Here 0,5,6,2 chain is repeated multiple times, is there a way to improve my code performance to avoid unnecessary similar loops like above.










share|improve this question























  • A bit of terminology, this kind of array (size n, containing n distinct ints) is a permutation and what you call a "chain" is a cycle.

    – David Soroko
    Nov 21 '18 at 19:32
















3















I am working on a program where I need to find out the maximum chain that can be formed from a given array.



Example:



Let's say input is :



Arr[0] = 5
Arr[1] = 4
Arr[2] = 0
Arr[3] = 3
Arr[4] = 1
Arr[5] = 6
Arr[6] = 2


Now if I take the array index and the corresponding value the possible max chain I can form is



index 0 with value 5 --> index 5 with value 6 --> index 6 with value 2 --> index 2 with value 0. This cycle repeats so this is my maximum chain i can form using this array



Here is my code:



public static int getMax(int nums) {
int result = 0;
for (int i = 0; i < nums.length; i++) {
List<Integer> list = new ArrayList<>();
list.add(i);
int temp = i;
while (true) {
int next = nums[temp];
if (list.contains(next)) {
break;
} else {
list.add(next);
temp = next;
}
}
result = Math.max(result, list.size());
}
return result;
}


I have come up with above logic but I see that in my code I am trying to find multiple chains of the same type.



It means if I print my list it has these values:



[0, 5, 6, 2]
[1, 4]
[2, 0, 5, 6]
[3]
[4, 1]
[5, 6, 2, 0]
[6, 2, 0, 5]


Here 0,5,6,2 chain is repeated multiple times, is there a way to improve my code performance to avoid unnecessary similar loops like above.










share|improve this question























  • A bit of terminology, this kind of array (size n, containing n distinct ints) is a permutation and what you call a "chain" is a cycle.

    – David Soroko
    Nov 21 '18 at 19:32














3












3








3








I am working on a program where I need to find out the maximum chain that can be formed from a given array.



Example:



Let's say input is :



Arr[0] = 5
Arr[1] = 4
Arr[2] = 0
Arr[3] = 3
Arr[4] = 1
Arr[5] = 6
Arr[6] = 2


Now if I take the array index and the corresponding value the possible max chain I can form is



index 0 with value 5 --> index 5 with value 6 --> index 6 with value 2 --> index 2 with value 0. This cycle repeats so this is my maximum chain i can form using this array



Here is my code:



public static int getMax(int nums) {
int result = 0;
for (int i = 0; i < nums.length; i++) {
List<Integer> list = new ArrayList<>();
list.add(i);
int temp = i;
while (true) {
int next = nums[temp];
if (list.contains(next)) {
break;
} else {
list.add(next);
temp = next;
}
}
result = Math.max(result, list.size());
}
return result;
}


I have come up with above logic but I see that in my code I am trying to find multiple chains of the same type.



It means if I print my list it has these values:



[0, 5, 6, 2]
[1, 4]
[2, 0, 5, 6]
[3]
[4, 1]
[5, 6, 2, 0]
[6, 2, 0, 5]


Here 0,5,6,2 chain is repeated multiple times, is there a way to improve my code performance to avoid unnecessary similar loops like above.










share|improve this question














I am working on a program where I need to find out the maximum chain that can be formed from a given array.



Example:



Let's say input is :



Arr[0] = 5
Arr[1] = 4
Arr[2] = 0
Arr[3] = 3
Arr[4] = 1
Arr[5] = 6
Arr[6] = 2


Now if I take the array index and the corresponding value the possible max chain I can form is



index 0 with value 5 --> index 5 with value 6 --> index 6 with value 2 --> index 2 with value 0. This cycle repeats so this is my maximum chain i can form using this array



Here is my code:



public static int getMax(int nums) {
int result = 0;
for (int i = 0; i < nums.length; i++) {
List<Integer> list = new ArrayList<>();
list.add(i);
int temp = i;
while (true) {
int next = nums[temp];
if (list.contains(next)) {
break;
} else {
list.add(next);
temp = next;
}
}
result = Math.max(result, list.size());
}
return result;
}


I have come up with above logic but I see that in my code I am trying to find multiple chains of the same type.



It means if I print my list it has these values:



[0, 5, 6, 2]
[1, 4]
[2, 0, 5, 6]
[3]
[4, 1]
[5, 6, 2, 0]
[6, 2, 0, 5]


Here 0,5,6,2 chain is repeated multiple times, is there a way to improve my code performance to avoid unnecessary similar loops like above.







java






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 '18 at 18:19









learnerlearner

1,69052854




1,69052854













  • A bit of terminology, this kind of array (size n, containing n distinct ints) is a permutation and what you call a "chain" is a cycle.

    – David Soroko
    Nov 21 '18 at 19:32



















  • A bit of terminology, this kind of array (size n, containing n distinct ints) is a permutation and what you call a "chain" is a cycle.

    – David Soroko
    Nov 21 '18 at 19:32

















A bit of terminology, this kind of array (size n, containing n distinct ints) is a permutation and what you call a "chain" is a cycle.

– David Soroko
Nov 21 '18 at 19:32





A bit of terminology, this kind of array (size n, containing n distinct ints) is a permutation and what you call a "chain" is a cycle.

– David Soroko
Nov 21 '18 at 19:32












3 Answers
3






active

oldest

votes


















2














You can put each values you get to an array by checking if that item is already contains in the array. Then when you iterate if you get a number in the array you filled, you can ignore that iteration by using continue






share|improve this answer































    1














    You can do it in two ways: you can make a list of used indices or you can create additional boolean array and there you can mark if this index was chosen. The second way is better, because you will not use a lot of additional memory, and also it will work faster. But the second way needs initialisation when first way does not.






    share|improve this answer































      1














      each chain is a directed path. Then you have a Graph(v,e) with v as each index and e as a pair (v1, v2) such that exist A[v1]=v2. Then, you can identify a path as a set of e. Therefore you can check if you already have covered a path storing each e that you have covered and comparing them agains the new ones.



      Like this:



          int nums = new int{5,4,0,3,1,6,2};
      int result = 0;
      List<String> coveredE = new ArrayList<>();
      for (int i = 0; i < nums.length; i++) {
      List<Integer> list = new ArrayList<>();
      list.add(i);
      int temp = i;
      // avoid covered edges
      if(coveredE.contains("("+temp+","+nums[temp]+")")) continue;
      while (true) {
      int next = nums[temp];
      // store covered edges
      coveredE.add("("+temp+","+next+")");
      if (list.contains(next)) {
      break;
      } else {
      list.add(next);
      temp = next;
      }
      }
      System.out.println(list);
      result = Math.max(result, list.size());
      }
      System.out.println(result);





      share|improve this answer

























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53418310%2ffind-max-length-of-elements-from-an-array%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        2














        You can put each values you get to an array by checking if that item is already contains in the array. Then when you iterate if you get a number in the array you filled, you can ignore that iteration by using continue






        share|improve this answer




























          2














          You can put each values you get to an array by checking if that item is already contains in the array. Then when you iterate if you get a number in the array you filled, you can ignore that iteration by using continue






          share|improve this answer


























            2












            2








            2







            You can put each values you get to an array by checking if that item is already contains in the array. Then when you iterate if you get a number in the array you filled, you can ignore that iteration by using continue






            share|improve this answer













            You can put each values you get to an array by checking if that item is already contains in the array. Then when you iterate if you get a number in the array you filled, you can ignore that iteration by using continue







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 21 '18 at 18:25









            SandSand

            1,7192722




            1,7192722

























                1














                You can do it in two ways: you can make a list of used indices or you can create additional boolean array and there you can mark if this index was chosen. The second way is better, because you will not use a lot of additional memory, and also it will work faster. But the second way needs initialisation when first way does not.






                share|improve this answer




























                  1














                  You can do it in two ways: you can make a list of used indices or you can create additional boolean array and there you can mark if this index was chosen. The second way is better, because you will not use a lot of additional memory, and also it will work faster. But the second way needs initialisation when first way does not.






                  share|improve this answer


























                    1












                    1








                    1







                    You can do it in two ways: you can make a list of used indices or you can create additional boolean array and there you can mark if this index was chosen. The second way is better, because you will not use a lot of additional memory, and also it will work faster. But the second way needs initialisation when first way does not.






                    share|improve this answer













                    You can do it in two ways: you can make a list of used indices or you can create additional boolean array and there you can mark if this index was chosen. The second way is better, because you will not use a lot of additional memory, and also it will work faster. But the second way needs initialisation when first way does not.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 21 '18 at 18:39









                    Dima RichDima Rich

                    514




                    514























                        1














                        each chain is a directed path. Then you have a Graph(v,e) with v as each index and e as a pair (v1, v2) such that exist A[v1]=v2. Then, you can identify a path as a set of e. Therefore you can check if you already have covered a path storing each e that you have covered and comparing them agains the new ones.



                        Like this:



                            int nums = new int{5,4,0,3,1,6,2};
                        int result = 0;
                        List<String> coveredE = new ArrayList<>();
                        for (int i = 0; i < nums.length; i++) {
                        List<Integer> list = new ArrayList<>();
                        list.add(i);
                        int temp = i;
                        // avoid covered edges
                        if(coveredE.contains("("+temp+","+nums[temp]+")")) continue;
                        while (true) {
                        int next = nums[temp];
                        // store covered edges
                        coveredE.add("("+temp+","+next+")");
                        if (list.contains(next)) {
                        break;
                        } else {
                        list.add(next);
                        temp = next;
                        }
                        }
                        System.out.println(list);
                        result = Math.max(result, list.size());
                        }
                        System.out.println(result);





                        share|improve this answer






























                          1














                          each chain is a directed path. Then you have a Graph(v,e) with v as each index and e as a pair (v1, v2) such that exist A[v1]=v2. Then, you can identify a path as a set of e. Therefore you can check if you already have covered a path storing each e that you have covered and comparing them agains the new ones.



                          Like this:



                              int nums = new int{5,4,0,3,1,6,2};
                          int result = 0;
                          List<String> coveredE = new ArrayList<>();
                          for (int i = 0; i < nums.length; i++) {
                          List<Integer> list = new ArrayList<>();
                          list.add(i);
                          int temp = i;
                          // avoid covered edges
                          if(coveredE.contains("("+temp+","+nums[temp]+")")) continue;
                          while (true) {
                          int next = nums[temp];
                          // store covered edges
                          coveredE.add("("+temp+","+next+")");
                          if (list.contains(next)) {
                          break;
                          } else {
                          list.add(next);
                          temp = next;
                          }
                          }
                          System.out.println(list);
                          result = Math.max(result, list.size());
                          }
                          System.out.println(result);





                          share|improve this answer




























                            1












                            1








                            1







                            each chain is a directed path. Then you have a Graph(v,e) with v as each index and e as a pair (v1, v2) such that exist A[v1]=v2. Then, you can identify a path as a set of e. Therefore you can check if you already have covered a path storing each e that you have covered and comparing them agains the new ones.



                            Like this:



                                int nums = new int{5,4,0,3,1,6,2};
                            int result = 0;
                            List<String> coveredE = new ArrayList<>();
                            for (int i = 0; i < nums.length; i++) {
                            List<Integer> list = new ArrayList<>();
                            list.add(i);
                            int temp = i;
                            // avoid covered edges
                            if(coveredE.contains("("+temp+","+nums[temp]+")")) continue;
                            while (true) {
                            int next = nums[temp];
                            // store covered edges
                            coveredE.add("("+temp+","+next+")");
                            if (list.contains(next)) {
                            break;
                            } else {
                            list.add(next);
                            temp = next;
                            }
                            }
                            System.out.println(list);
                            result = Math.max(result, list.size());
                            }
                            System.out.println(result);





                            share|improve this answer















                            each chain is a directed path. Then you have a Graph(v,e) with v as each index and e as a pair (v1, v2) such that exist A[v1]=v2. Then, you can identify a path as a set of e. Therefore you can check if you already have covered a path storing each e that you have covered and comparing them agains the new ones.



                            Like this:



                                int nums = new int{5,4,0,3,1,6,2};
                            int result = 0;
                            List<String> coveredE = new ArrayList<>();
                            for (int i = 0; i < nums.length; i++) {
                            List<Integer> list = new ArrayList<>();
                            list.add(i);
                            int temp = i;
                            // avoid covered edges
                            if(coveredE.contains("("+temp+","+nums[temp]+")")) continue;
                            while (true) {
                            int next = nums[temp];
                            // store covered edges
                            coveredE.add("("+temp+","+next+")");
                            if (list.contains(next)) {
                            break;
                            } else {
                            list.add(next);
                            temp = next;
                            }
                            }
                            System.out.println(list);
                            result = Math.max(result, list.size());
                            }
                            System.out.println(result);






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 21 '18 at 18:57

























                            answered Nov 21 '18 at 18:51









                            elbraulioelbraulio

                            742214




                            742214






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53418310%2ffind-max-length-of-elements-from-an-array%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                這個網誌中的熱門文章

                                Academy of Television Arts & Sciences

                                L'Équipe

                                1995 France bombings