complexity O (N) and complexity of the space O (1) . This is the best solution I know:
#include <stdio.h>
Here are some test cases:
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, &start, &end); printf("sum: %d, start: %d, end: %d\n", sum, start, end); sum = get_max_sum(arr2, 1, &start, &end); printf("sum: %d, start: %d, end: %d\n", sum, start, end); sum = get_max_sum(arr3, 4, &start, &end); printf("sum: %d, start: %d, end: %d\n", sum, start, end); sum = get_max_sum(arr4, 6, &start, &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
Update1 : Added code for printing subarray index.
Update2 : If two auxiliary arrays with the same sum are found, select one element with a large number of elements.
Update3 : Fix algorithm for leading negative numbers