当前位置: 代码迷 >> 综合 >> [LeetCode] 050: Maximum Subarray
  详细解决方案

[LeetCode] 050: Maximum Subarray

热度:71   发布时间:2023-12-09 05:49:20.0
[Problem]

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.


[Solution]

class Solution {
   
public:
int maxSubArray(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n <= 0)return 0;
int sum[n], res = A[0];
for(int i = 0; i < n; ++i){
if(i == 0){
sum[i] = A[i];
}
else{
sum[i] = max(sum[i-1] + A[i], A[i]);
}
res = max(res, sum[i]);
}
return res;
}
};
说明:版权所有,转载请注明出处。 Coder007的博客
  相关解决方案