Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>O(N) time complexity and O(1) space complexity</strong>. This is the optimal solution I know:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;limits.h&gt; int get_max_sum(int* array, int len, int* start, int* end) { int max_sum = INT_MIN, sum = 0, i; int tmp_start = 0; for(i = 0; i != len; ++i) { sum += array[i]; // if the sum is equal, choose the one with more elements if(sum &gt; max_sum || (sum == max_sum &amp;&amp; (end - start) &lt; (i - tmp_start))) { max_sum = sum; *start = tmp_start; *end = i; } if(sum &lt; 0) { sum = 0; tmp_start = i + 1; } } return max_sum; } </code></pre> <p>Here are some test cases:</p> <pre><code>int main(int argc, char **argv) { int arr1[] = {5, 1, -7, 3, 7}; int arr2[] = {1}; int arr3[] = {-1, -7, -3, -7}; int arr4[] = {5, 1, -7, 2, 2, 2}; int start, end, sum; sum = get_max_sum(arr1, 5, &amp;start, &amp;end); printf("sum: %d, start: %d, end: %d\n", sum, start, end); sum = get_max_sum(arr2, 1, &amp;start, &amp;end); printf("sum: %d, start: %d, end: %d\n", sum, start, end); sum = get_max_sum(arr3, 4, &amp;start, &amp;end); printf("sum: %d, start: %d, end: %d\n", sum, start, end); sum = get_max_sum(arr4, 6, &amp;start, &amp;end); printf("sum: %d, start: %d, end: %d\n", sum, start, end); return 0; } $ ./a.out sum: 10, start: 3, end: 4 sum: 1, start: 0, end: 0 sum: -1, start: 0, end: 0 sum: 6, start: 3, end: 5 </code></pre> <p><strong>Update1</strong>: Added code to print the index of the subarray.</p> <p><strong>Update2</strong>: If two sub arrays with the same sum are found, choose the one with more elements.</p> <p><strong>Update3</strong>: Fix the algorithm for leading negative numbers</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload