Find the maximum interval sum in a list of real numbers

后端 未结 9 1358
长情又很酷
长情又很酷 2020-12-10 17:20

Here\'s an interview questions that a colleague asked for a programming position. I thought this was great for watching the interviewee think it through. I\'d love to get re

9条回答
  •  旧巷少年郎
    2020-12-10 18:01

    We can just use the easiest 2 lines of code algo, it's simple and handles all negative as well :)

    curr_max = max(a[i], curr_max+a[i]);

    max_so_far = max(max_so_far, curr_max;

    eg. C++

    int maxSubArraySum(int a[], int size) 
    { 
        int max_so_far = a[0]; 
        int curr_max = a[0]; 
    
        for (int i = 1; i < size; i++) 
        { 
             curr_max = max(a[i], curr_max+a[i]); 
             max_so_far = max(max_so_far, curr_max; 
        }  
        return max_so_far; 
     } 
    

提交回复
热议问题