-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterval_maxSum.c
59 lines (43 loc) · 1.19 KB
/
interval_maxSum.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define ARRAY_SIZE 8
int MAX_INT = ((unsigned)(-1)) >> 1;
int inefficientMaxSum(int arrayList[], int size);
int betterMaxSum(int arrayList[], int size);
int main(int argc, char *argv[]) {
int array[ARRAY_SIZE] = {
-7, 4, -3, 6, 3, -8, 3, 4
};
printf("1\\Max interval Sum = %d\n", inefficientMaxSum(array, ARRAY_SIZE));
printf("2\\Max interval Sum = %d\n", betterMaxSum(array, ARRAY_SIZE));
return 0;
}
int betterMaxSum(int arrayList[], int size) {
int sum, maxSum = ~MAX_INT;
int i, j;
for (i = 0; i < size; i++) {
sum = 0;
for (j = i; j < size; j++) {
sum += arrayList[j];
maxSum = MAX(maxSum, sum);
}
}
return maxSum;
}
int inefficientMaxSum(int arrayList[], int size) {
int sum, maxSum = ~MAX_INT;
int i, j, k;
for (i = 0; i < size; i++) {
for (j = i; j < size; j++) {
sum = 0;
for (k = i; k < j; k++) {
sum += arrayList[k];
}
maxSum = MAX(maxSum, sum);
}
}
return maxSum;
}