Max Sum Contiguous Subarray

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
4
down vote

favorite












This is a maximum sum contiguous problem from interviewbit.com




Problem : Find the contiguous subarray within an array (containing at least one number) which has the largest sum.



For example: Given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6.




This is my solution :



def max_sub_array(array):
""" Finds msub-array with maximum sum and returns the maximum sum and sub-array"""
max_start, max_stop = 0, 1 # Start, Stop of maximum sub-array
curr = 0 # pointer to current array
max_sum = array[0] # Sum of maximum array
current_sum = 0 # sum of current array

for i, elem in enumerate(array):
current_sum += elem

if max_sum < current_sum:
max_sum = current_sum
max_start = curr
max_stop = i + 1
if current_sum < 0:
current_sum = 0
curr = i + 1

return max_sum , array[max_start:max_stop]


checking test cases:



assert max_sub_array([-4,-2,-3,-4,-5]) == (-2,[-2]), "Wrong evaluation"
assert max_sub_array([-1]) == (-1,[-1]), "Wrong evaluation"
assert max_sub_array([-5, 1, -3, 7, -1, 2, 1, -4, 6]) == (11,[7, -1, 2, 1, -4, 6]), "Wrong evaluation"
assert max_sub_array([-5, 1, -3, 7, -1, 2, 1, -6, 5]) == (9, [7, -1, 2, 1]), "Wrong evaluation"
assert max_sub_array( [6, -3, -2, 7, -5, 2, 1, -7, 6]) == (8,[6, -3, -2, 7]), "Wrong evaluation"
assert max_sub_array([-5, -2, -1, -4, -7]) == (-1,[-1]), "Wrong evaluation"
assert max_sub_array( [4, 1, 1, 4, -4, 10, -4, 10, 3, -3, -9, -8, 2, -6, -6, -5, -1, -7, 7, 8]) == (25,[4, 1, 1, 4, -4, 10, -4, 10, 3]), "Wrong evaluation"
assert max_sub_array([4, -5, -1, 0, -2, 20, -4, -3, -2, 8, -1, 10, -1, -1 ]) == (28, [20, -4, -3, -2, 8, -1, 10]), "Wrong evaluation"


How can this code be optimised ?







share|improve this question














bumped to the homepage by Community♦ 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.














  • It is a known problem in computer science as @kaushal says. Kadane's algorithm is $O(n)$ (linear run time complexity) and is probably as good as it gets.
    – esote
    Jul 10 at 2:27

















up vote
4
down vote

favorite












This is a maximum sum contiguous problem from interviewbit.com




Problem : Find the contiguous subarray within an array (containing at least one number) which has the largest sum.



For example: Given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6.




This is my solution :



def max_sub_array(array):
""" Finds msub-array with maximum sum and returns the maximum sum and sub-array"""
max_start, max_stop = 0, 1 # Start, Stop of maximum sub-array
curr = 0 # pointer to current array
max_sum = array[0] # Sum of maximum array
current_sum = 0 # sum of current array

for i, elem in enumerate(array):
current_sum += elem

if max_sum < current_sum:
max_sum = current_sum
max_start = curr
max_stop = i + 1
if current_sum < 0:
current_sum = 0
curr = i + 1

return max_sum , array[max_start:max_stop]


checking test cases:



assert max_sub_array([-4,-2,-3,-4,-5]) == (-2,[-2]), "Wrong evaluation"
assert max_sub_array([-1]) == (-1,[-1]), "Wrong evaluation"
assert max_sub_array([-5, 1, -3, 7, -1, 2, 1, -4, 6]) == (11,[7, -1, 2, 1, -4, 6]), "Wrong evaluation"
assert max_sub_array([-5, 1, -3, 7, -1, 2, 1, -6, 5]) == (9, [7, -1, 2, 1]), "Wrong evaluation"
assert max_sub_array( [6, -3, -2, 7, -5, 2, 1, -7, 6]) == (8,[6, -3, -2, 7]), "Wrong evaluation"
assert max_sub_array([-5, -2, -1, -4, -7]) == (-1,[-1]), "Wrong evaluation"
assert max_sub_array( [4, 1, 1, 4, -4, 10, -4, 10, 3, -3, -9, -8, 2, -6, -6, -5, -1, -7, 7, 8]) == (25,[4, 1, 1, 4, -4, 10, -4, 10, 3]), "Wrong evaluation"
assert max_sub_array([4, -5, -1, 0, -2, 20, -4, -3, -2, 8, -1, 10, -1, -1 ]) == (28, [20, -4, -3, -2, 8, -1, 10]), "Wrong evaluation"


How can this code be optimised ?







share|improve this question














bumped to the homepage by Community♦ 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.














  • It is a known problem in computer science as @kaushal says. Kadane's algorithm is $O(n)$ (linear run time complexity) and is probably as good as it gets.
    – esote
    Jul 10 at 2:27













up vote
4
down vote

favorite









up vote
4
down vote

favorite











This is a maximum sum contiguous problem from interviewbit.com




Problem : Find the contiguous subarray within an array (containing at least one number) which has the largest sum.



For example: Given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6.




This is my solution :



def max_sub_array(array):
""" Finds msub-array with maximum sum and returns the maximum sum and sub-array"""
max_start, max_stop = 0, 1 # Start, Stop of maximum sub-array
curr = 0 # pointer to current array
max_sum = array[0] # Sum of maximum array
current_sum = 0 # sum of current array

for i, elem in enumerate(array):
current_sum += elem

if max_sum < current_sum:
max_sum = current_sum
max_start = curr
max_stop = i + 1
if current_sum < 0:
current_sum = 0
curr = i + 1

return max_sum , array[max_start:max_stop]


checking test cases:



assert max_sub_array([-4,-2,-3,-4,-5]) == (-2,[-2]), "Wrong evaluation"
assert max_sub_array([-1]) == (-1,[-1]), "Wrong evaluation"
assert max_sub_array([-5, 1, -3, 7, -1, 2, 1, -4, 6]) == (11,[7, -1, 2, 1, -4, 6]), "Wrong evaluation"
assert max_sub_array([-5, 1, -3, 7, -1, 2, 1, -6, 5]) == (9, [7, -1, 2, 1]), "Wrong evaluation"
assert max_sub_array( [6, -3, -2, 7, -5, 2, 1, -7, 6]) == (8,[6, -3, -2, 7]), "Wrong evaluation"
assert max_sub_array([-5, -2, -1, -4, -7]) == (-1,[-1]), "Wrong evaluation"
assert max_sub_array( [4, 1, 1, 4, -4, 10, -4, 10, 3, -3, -9, -8, 2, -6, -6, -5, -1, -7, 7, 8]) == (25,[4, 1, 1, 4, -4, 10, -4, 10, 3]), "Wrong evaluation"
assert max_sub_array([4, -5, -1, 0, -2, 20, -4, -3, -2, 8, -1, 10, -1, -1 ]) == (28, [20, -4, -3, -2, 8, -1, 10]), "Wrong evaluation"


How can this code be optimised ?







share|improve this question













This is a maximum sum contiguous problem from interviewbit.com




Problem : Find the contiguous subarray within an array (containing at least one number) which has the largest sum.



For example: Given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6.




This is my solution :



def max_sub_array(array):
""" Finds msub-array with maximum sum and returns the maximum sum and sub-array"""
max_start, max_stop = 0, 1 # Start, Stop of maximum sub-array
curr = 0 # pointer to current array
max_sum = array[0] # Sum of maximum array
current_sum = 0 # sum of current array

for i, elem in enumerate(array):
current_sum += elem

if max_sum < current_sum:
max_sum = current_sum
max_start = curr
max_stop = i + 1
if current_sum < 0:
current_sum = 0
curr = i + 1

return max_sum , array[max_start:max_stop]


checking test cases:



assert max_sub_array([-4,-2,-3,-4,-5]) == (-2,[-2]), "Wrong evaluation"
assert max_sub_array([-1]) == (-1,[-1]), "Wrong evaluation"
assert max_sub_array([-5, 1, -3, 7, -1, 2, 1, -4, 6]) == (11,[7, -1, 2, 1, -4, 6]), "Wrong evaluation"
assert max_sub_array([-5, 1, -3, 7, -1, 2, 1, -6, 5]) == (9, [7, -1, 2, 1]), "Wrong evaluation"
assert max_sub_array( [6, -3, -2, 7, -5, 2, 1, -7, 6]) == (8,[6, -3, -2, 7]), "Wrong evaluation"
assert max_sub_array([-5, -2, -1, -4, -7]) == (-1,[-1]), "Wrong evaluation"
assert max_sub_array( [4, 1, 1, 4, -4, 10, -4, 10, 3, -3, -9, -8, 2, -6, -6, -5, -1, -7, 7, 8]) == (25,[4, 1, 1, 4, -4, 10, -4, 10, 3]), "Wrong evaluation"
assert max_sub_array([4, -5, -1, 0, -2, 20, -4, -3, -2, 8, -1, 10, -1, -1 ]) == (28, [20, -4, -3, -2, 8, -1, 10]), "Wrong evaluation"


How can this code be optimised ?









share|improve this question












share|improve this question




share|improve this question








edited May 10 at 18:18









Sam Onela

5,77461543




5,77461543









asked May 10 at 17:35









Latika Agarwal

861216




861216





bumped to the homepage by Community♦ 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community♦ 2 days ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.













  • It is a known problem in computer science as @kaushal says. Kadane's algorithm is $O(n)$ (linear run time complexity) and is probably as good as it gets.
    – esote
    Jul 10 at 2:27

















  • It is a known problem in computer science as @kaushal says. Kadane's algorithm is $O(n)$ (linear run time complexity) and is probably as good as it gets.
    – esote
    Jul 10 at 2:27
















It is a known problem in computer science as @kaushal says. Kadane's algorithm is $O(n)$ (linear run time complexity) and is probably as good as it gets.
– esote
Jul 10 at 2:27





It is a known problem in computer science as @kaushal says. Kadane's algorithm is $O(n)$ (linear run time complexity) and is probably as good as it gets.
– esote
Jul 10 at 2:27











2 Answers
2






active

oldest

votes

















up vote
0
down vote













It goes without saying that this is a well known problem. ref



Your code is already linear in the input, takes a single pass over the array, and does the minimum possible checks (if statements) and update assignments for the involved variables.



It cannot be optimised any further.






share|improve this answer

















  • 2




    Welcome to Code Review! Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
    – Dannnno
    May 10 at 22:49

















up vote
0
down vote













Expanding upon my comment:



Here is Kadane's algorithm:



def max_subarray(arr):
max_ending = max_current = arr[0]

for i in arr[1:]:
max_ending = max(i, max_ending + i)
max_current = max(max_current, max_ending)

return max_current

print(max_subarray([-4, -2, -3, -4, 5])) # 5

print(max_subarray([4, -5, -1, 0, -2, 20, -4, -3, -2, 8, -1, 10, -1, -1])) # 28


Like your algorithm, it is $O(n)$. However, it does fewer operations while looping. You could then alter it to return the array which gives that sum, which shouldn't be too hard.






share|improve this answer





















    Your Answer




    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    );
    );
    , "mathjax-editing");

    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: "196"
    ;
    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',
    convertImagesToLinks: false,
    noModals: false,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );








     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f194126%2fmax-sum-contiguous-subarray%23new-answer', 'question_page');

    );

    Post as a guest






























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    It goes without saying that this is a well known problem. ref



    Your code is already linear in the input, takes a single pass over the array, and does the minimum possible checks (if statements) and update assignments for the involved variables.



    It cannot be optimised any further.






    share|improve this answer

















    • 2




      Welcome to Code Review! Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
      – Dannnno
      May 10 at 22:49














    up vote
    0
    down vote













    It goes without saying that this is a well known problem. ref



    Your code is already linear in the input, takes a single pass over the array, and does the minimum possible checks (if statements) and update assignments for the involved variables.



    It cannot be optimised any further.






    share|improve this answer

















    • 2




      Welcome to Code Review! Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
      – Dannnno
      May 10 at 22:49












    up vote
    0
    down vote










    up vote
    0
    down vote









    It goes without saying that this is a well known problem. ref



    Your code is already linear in the input, takes a single pass over the array, and does the minimum possible checks (if statements) and update assignments for the involved variables.



    It cannot be optimised any further.






    share|improve this answer













    It goes without saying that this is a well known problem. ref



    Your code is already linear in the input, takes a single pass over the array, and does the minimum possible checks (if statements) and update assignments for the involved variables.



    It cannot be optimised any further.







    share|improve this answer













    share|improve this answer



    share|improve this answer











    answered May 10 at 22:07









    kaushal agrawal

    11




    11







    • 2




      Welcome to Code Review! Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
      – Dannnno
      May 10 at 22:49












    • 2




      Welcome to Code Review! Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
      – Dannnno
      May 10 at 22:49







    2




    2




    Welcome to Code Review! Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
    – Dannnno
    May 10 at 22:49




    Welcome to Code Review! Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
    – Dannnno
    May 10 at 22:49












    up vote
    0
    down vote













    Expanding upon my comment:



    Here is Kadane's algorithm:



    def max_subarray(arr):
    max_ending = max_current = arr[0]

    for i in arr[1:]:
    max_ending = max(i, max_ending + i)
    max_current = max(max_current, max_ending)

    return max_current

    print(max_subarray([-4, -2, -3, -4, 5])) # 5

    print(max_subarray([4, -5, -1, 0, -2, 20, -4, -3, -2, 8, -1, 10, -1, -1])) # 28


    Like your algorithm, it is $O(n)$. However, it does fewer operations while looping. You could then alter it to return the array which gives that sum, which shouldn't be too hard.






    share|improve this answer

























      up vote
      0
      down vote













      Expanding upon my comment:



      Here is Kadane's algorithm:



      def max_subarray(arr):
      max_ending = max_current = arr[0]

      for i in arr[1:]:
      max_ending = max(i, max_ending + i)
      max_current = max(max_current, max_ending)

      return max_current

      print(max_subarray([-4, -2, -3, -4, 5])) # 5

      print(max_subarray([4, -5, -1, 0, -2, 20, -4, -3, -2, 8, -1, 10, -1, -1])) # 28


      Like your algorithm, it is $O(n)$. However, it does fewer operations while looping. You could then alter it to return the array which gives that sum, which shouldn't be too hard.






      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        Expanding upon my comment:



        Here is Kadane's algorithm:



        def max_subarray(arr):
        max_ending = max_current = arr[0]

        for i in arr[1:]:
        max_ending = max(i, max_ending + i)
        max_current = max(max_current, max_ending)

        return max_current

        print(max_subarray([-4, -2, -3, -4, 5])) # 5

        print(max_subarray([4, -5, -1, 0, -2, 20, -4, -3, -2, 8, -1, 10, -1, -1])) # 28


        Like your algorithm, it is $O(n)$. However, it does fewer operations while looping. You could then alter it to return the array which gives that sum, which shouldn't be too hard.






        share|improve this answer













        Expanding upon my comment:



        Here is Kadane's algorithm:



        def max_subarray(arr):
        max_ending = max_current = arr[0]

        for i in arr[1:]:
        max_ending = max(i, max_ending + i)
        max_current = max(max_current, max_ending)

        return max_current

        print(max_subarray([-4, -2, -3, -4, 5])) # 5

        print(max_subarray([4, -5, -1, 0, -2, 20, -4, -3, -2, 8, -1, 10, -1, -1])) # 28


        Like your algorithm, it is $O(n)$. However, it does fewer operations while looping. You could then alter it to return the array which gives that sum, which shouldn't be too hard.







        share|improve this answer













        share|improve this answer



        share|improve this answer











        answered Jul 10 at 12:32









        esote

        1,203428




        1,203428






















             

            draft saved


            draft discarded


























             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f194126%2fmax-sum-contiguous-subarray%23new-answer', 'question_page');

            );

            Post as a guest













































































            Popular posts from this blog

            Chat program with C++ and SFML

            Function to Return a JSON Like Objects Using VBA Collections and Arrays

            Will my employers contract hold up in court?