leetcode_question_53 Maximum Subarray
来源:互联网 发布:关于大数据存储论文 编辑:程序博客网 时间:2024/06/03 09:53
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
.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
dp:
int maxSubArray(int A[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int max = A[0]; int currentsum = A[0]; for(int i = 1; i < n; ++i){ if(currentsum < 0) currentsum = 0; currentsum += A[i]; if(currentsum > max) max = currentsum; } return max; }
Divide and Conquer:
int calmaxsubarr(int A[], int begin, int end){ if(begin == end) return A[begin]; int mid = (end-begin)/2 + begin; int left = calmaxsubarr(A, begin, mid); int right = calmaxsubarr(A, mid+1, end); int lefthalf = A[mid]; int tmp = A[mid]; for(int i = mid -1; i >= begin; i--){ tmp += A[i]; if(tmp > lefthalf) lefthalf = tmp; } int righthalf = A[mid+1]; tmp = A[mid+1]; for(int i = mid +2; i <= end; ++i){ tmp += A[i]; if(tmp > righthalf)righthalf = tmp; } int middle = lefthalf + righthalf; int res = left > right ? left : right; res = res > middle ? res : middle; return res; } int maxSubArray(int A[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function return calmaxsubarr(A, 0, n-1); }
- leetcode_question_53 Maximum Subarray
- maximum subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- Maximum Subarray
- linux安装jdk
- 习题2-5 统计
- ExtJS-4
- Lttng
- StringBuffer内容清空效率比较
- leetcode_question_53 Maximum Subarray
- Remove Duplicates from Sorted List II
- 启动Strut时出现异常: Unable to load configuration. - bean
- 九度OnlineJudge之1022:游船出租
- flume-ng 使用系列
- ftrace 简介
- linux编程主题之进程
- c++ hash_map 详细介绍
- oracle参数文件、控制文件、数据文件、日志文件存放位置查看