首页 > 代码库 > [leetcode]Maximum Subarray
[leetcode]Maximum Subarray
问题描述:
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
.
基本思路:
遍历并记录最大的subarray值。O(n)时间算法
代码:
int maxSubArray(int A[], int n) { //C++ int max = A[0]; int tmp = 0; for(int i = 0; i < n; i++) { tmp += A[i]; if(tmp > max) max = tmp; if(tmp < 0){ tmp = 0; } } return max; }
分治法
int divideConquer(int A[], int low, int high){ //C++ if(low == high) return A[low]; int mid = (low + high)/2; int sum1 = divideConquer(A, low , mid); int sum2 = divideConquer(A, mid+1, high); int sum3 = findMidMax(A,low,high,mid); int max; max = (sum1 > sum2)? sum1:sum2; max = (max > sum3)? max: sum3; // cout << low << high << mid <<max; return max; } int findMidMax(int A[] , int low , int high, int mid){ int max = A[mid],tmp = 0,sum = 0; int i = mid; while(i >= low ) { tmp +=A[i]; if(tmp > max) max = tmp; i--; } sum = max; max = 0 , tmp = 0; int j = mid+1; while(j <= high) { tmp +=A[j]; if(tmp > max) max = tmp; j++; } sum += max; return sum; } int maxSubArray(int A[], int n) { return divideConquer(A,0,n-1); }
[leetcode]Maximum Subarray
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。