首页 > 代码库 > 53.Maximum Subarray(法1线性扫面法2分治法)
53.Maximum Subarray(法1线性扫面法2分治法)
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.
click to showmore practice.
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"); }
53.Maximum Subarray(法1线性扫面法2分治法)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。