132 lines
2.5 KiB
C
132 lines
2.5 KiB
C
#include <stdio.h>
|
|
|
|
int MSS1(const int A[], int N) {
|
|
int thisSum, maxSum, i, j, k;
|
|
|
|
maxSum = 0;
|
|
int counter = 1;
|
|
|
|
printf("Algo 1\n");
|
|
|
|
for (i = 0; i < N; i++) {
|
|
for (j = i; j < N; j++) {
|
|
printf("%d run: (%d, %d)\n", counter++, thisSum, maxSum);
|
|
thisSum = 0;
|
|
for (k = i; k <= j; k++) {
|
|
thisSum += A[k];
|
|
}
|
|
|
|
if (thisSum > maxSum) {
|
|
maxSum = thisSum;
|
|
}
|
|
}
|
|
}
|
|
|
|
return maxSum;
|
|
}
|
|
|
|
int MSS2(const int A[], int N) {
|
|
int thisSum, maxSum, i, j;
|
|
|
|
maxSum = 0;
|
|
int counter = 1;
|
|
|
|
printf("Algo 2\n");
|
|
|
|
for (i = 0; i < N; i++) {
|
|
thisSum = 0;
|
|
for (j = i; j < N; j++) {
|
|
printf("%d run: (%d, %d)\n", counter++, thisSum, maxSum);
|
|
thisSum += A[j];
|
|
|
|
if (thisSum > maxSum) {
|
|
maxSum = thisSum;
|
|
}
|
|
}
|
|
}
|
|
|
|
return maxSum;
|
|
}
|
|
|
|
int Max3(int i, int j, int k) {
|
|
int max = i;
|
|
if (j > max) {
|
|
max = j;
|
|
}
|
|
|
|
if (k > max) {
|
|
max = k;
|
|
}
|
|
|
|
return max;
|
|
}
|
|
|
|
static int MaxSubSum(const int A[], int Left, int Right) {
|
|
int MaxLeftSum, MaxRightSum;
|
|
int MaxLeftBorderSum, MaxRightBorderSum;
|
|
|
|
int LeftBorderSum, RightBorderSum;
|
|
|
|
int Center, i;
|
|
|
|
if (Left == Right) /* Base Case */
|
|
if (A[Left] > 0)
|
|
return A[Left];
|
|
else
|
|
return 0;
|
|
|
|
Center = (Left + Right) / 2;
|
|
MaxLeftSum = MaxSubSum(A, Left, Center);
|
|
MaxRightSum = MaxSubSum(A, Center + 1, Right);
|
|
|
|
MaxLeftBorderSum = 0;
|
|
LeftBorderSum = 0;
|
|
|
|
for (i = Center; i >= Left; i--)
|
|
LeftBorderSum += A[i];
|
|
if (LeftBorderSum > MaxLeftBorderSum)
|
|
MaxLeftBorderSum = LeftBorderSum;
|
|
|
|
MaxRightBorderSum = 0;
|
|
RightBorderSum = 0;
|
|
for (i = Center + 1; i <= Right; i++)
|
|
|
|
{
|
|
RightBorderSum += A[i];
|
|
if (RightBorderSum > MaxRightBorderSum)
|
|
MaxRightBorderSum = RightBorderSum;
|
|
}
|
|
printf("MLS: %d, MRS: %d, MLBS: %d, MRBS: %d\n", MaxLeftSum, MaxRightSum,
|
|
MaxLeftBorderSum, MaxRightBorderSum);
|
|
return Max3(MaxLeftSum, MaxRightSum, MaxLeftBorderSum + MaxRightBorderSum);
|
|
}
|
|
|
|
int MSS4(const int A[], int N) {
|
|
int thisSum, maxSum, j;
|
|
|
|
thisSum = maxSum = 0;
|
|
int counter = 1;
|
|
|
|
for (j = 0; j < N; j++) {
|
|
printf("%d run: (%d, %d) \n", counter++, thisSum, maxSum);
|
|
thisSum += A[j];
|
|
|
|
if (thisSum > maxSum) {
|
|
maxSum = thisSum;
|
|
} else if (thisSum < 0) {
|
|
thisSum = 0;
|
|
}
|
|
}
|
|
|
|
return maxSum;
|
|
}
|
|
|
|
int main(void) {
|
|
const int input[] = {4, -3, 5, -2, -1, 2, 6, -2};
|
|
const int N = 8;
|
|
|
|
// printf("Answer: %d", MaxSubSum(input, 0, N - 1));
|
|
printf("Answer: %d", MSS4(input, N));
|
|
return 0;
|
|
}
|