Maximum Subarray(最大连续子数组之和)

it2022-05-05  268

描述 Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6.

#include <stdio.h> #include <limits.h> #define max(a,b) (a)>(b)?(a):(b) int subMaxSum(int A[], int n) { int f = 0, i; int result = INT_MIN; for (i = 0; i < n; i++) { f = max(f+A[i], A[i]); result = max(result, f); } return result; } int main(int argc, char *argv[]) { int A[9] = {-2,1,-3,4,-1,2,1,-5,4}; int res = subMaxSum(A, 9); printf("%d\n", res); return 0; }

 


最新回复(0)