首页 > 代码库 > LeetCode Maximum Subarray
LeetCode Maximum Subarray
class Solution {public: int maxSubArray(int A[], int n) { int cur_sum = 0; int max_sum = INT_MIN; for (int i=0; i<n; i++) { cur_sum += A[i]; if (cur_sum > max_sum) max_sum = cur_sum; if (cur_sum < 0) { cur_sum = 0; } } return max_sum; }};
老题
分治法,nlogn, 但是TLE
class Solution {public:int maxSubArray(int A[], int n) { return dfs(A, 0, n); } int dfs(int A[], int start, int end) { if (start >= end) { cout<<"range error: start="<<start<<", end="<<end<<endl; return INT_MIN; } if (start + 1 == end) return A[start]; int mid = (start + end) / 2; int ma = dfs(A, start, mid); int mb = dfs(A, mid, end); int maxsum = ma > mb ? ma : mb; int lsum = 0, rsum = 0; int lmax = INT_MIN, rmax = INT_MIN; for (int i=mid - 1; i>=0; i--) { lsum += A[i]; if (lsum > lmax) lmax = lsum; } for (int i=mid; i<end; i++) { rsum += A[i]; if (rsum > rmax) rmax = rsum; } if (lmax + rmax > maxsum) maxsum = lmax + rmax; return maxsum; };};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。