随笔- 509  文章- 0  评论- 151  阅读- 22万 

Maximum Subarray

2013.12.17 14:21

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.

click to show more practice.

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:
  This is a typical problem on any Data Structure textbook. Need no further explanation.
  Time complexity is O(n), space complexity O(1).
Accepted code:
复制代码
 1 //#define __MAIN__
 2 #include <cstdio>
 3 #include <cstdlib>
 4 using namespace std;
 5 
 6 class Solution {
 7 public:
 8     int maxSubArray(int A[], int n) {
 9         // Note: The Solution object is instantiated only once and is reused by each test case.
10         if(A == nullptr){
11             return 0;
12         }
13 
14         if(n <= 0){
15             return 0;
16         }
17 
18         int i;
19         int max_value;
20 
21         max_value = A[0];
22         for(i = 0; i < n; ++i){
23             if(A[i] > max_value){
24                 max_value = A[i];
25             }
26             if(A[i] >= 0){
27                 break;
28             }
29         }
30 
31         if(i >= n && max_value <= 0){
32             // All A[i]s are 0 or negative.
33             return max_value;
34         }
35 
36         int sum, max_sum;
37 
38         sum = max_sum = 0;
39         for(i = 0; i < n; ++i){
40             sum += A[i];
41             if(sum < 0){
42                 sum = 0;
43             }
44             if(sum > max_sum){
45                 max_sum = sum;
46             }
47         }
48 
49         return max_sum;
50     }
51 };
52 
53 #ifdef __MAIN__
54 int main()
55 {
56     Solution sol;
57     int A[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
58     const int n = sizeof(A) / sizeof(int);
59 
60     printf("%d\n", sol.maxSubArray(A, n));
61 
62     return 0;
63 }
64 #endif
复制代码

 

 posted on   zhuli19901106  阅读(206)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示