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
.
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)