Find the contiguous subarray within an array (containing at least onenumber) 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 thelargest sum = 6.
HideTags
Divide and Conquer Array Dynamic
Programming
#include<iostream> using namespace std; //取大值 int max(int a, int b, int c) { if (a > b) if (a > c) return a; else return c; else if (c > b) return c; return b; } //flag=1,返回与A同尾的子数组的最大值,flag=0,返回与A同头的子数组的最大值 int maxSideArray(int *A, int n, int flag) { if (flag)//返回与A同尾的子数组的最大值 { int sum = 0; int maxsum = A[n - 1]; for (int i = n - 1; i >= 0; i--) { sum += A[i]; if (sum > maxsum) maxsum = sum; } return maxsum; } else//返回与A同头的子数组的最大值 { int sum = 0; int maxsum = A[0]; for (int i = 0; i < n; i++) { sum += A[i]; if (sum > maxsum) maxsum = sum; } return maxsum; } } //法2:分而治之 int maxSubArray2(int A[], int n) { if (n == 1) return *A; //左半部分最大值,有半部分最大值,跨过中线的最大值:三个值取最大 return max(maxSubArray2(A, n / 2), maxSubArray2(A + n / 2, n - n / 2), maxSideArray(A, n / 2, 1) + maxSideArray(A + n / 2, n - n / 2, 0)); } //法1:线性扫描 int maxSubArray(int A[], int n) { int sum = 0; int maxsum = A[0]; for (int i = 0; i < n; i++) { sum += A[i]; if (sum > maxsum) maxsum = sum; if (sum < 0) sum = 0; } return maxsum; } void main() { int A[] = { 1, -8, 6, 3, -1, 5, 7, -2, 0, 1 }; int B[] = { -2, 1 }; cout << maxSubArray(A, 10) << endl; cout << maxSubArray(B, 2) << endl; cout << maxSubArray2(A, 10) << endl; cout << maxSubArray2(B, 2) << endl; system("pause"); }
时间: 2024-10-18 21:56:36