[LeetCode] Maximum Subarray Sum
Dynamic Programming
There is a nice introduction to the DP algorithm in this Wikipedia article. The idea is to maintain a running maximum smax
and a current summation sum
. When we visit each num
in nums
, addnum
to sum
, then update smax
if necessary or reset sum
to 0
if it becomes negative.
The code is as follows.
1 class Solution { 2 public: 3 int maxSubArray(vector<int>& nums) { 4 int sum = 0, smax = INT_MIN; 5 for (int num : nums) { 6 sum += num; 7 if (sum > smax) smax = sum; 8 if (sum < 0) sum = 0; 9 } 10 return smax; 11 } 12 };
Divide and Conquer
The DC algorithm breaks nums
into two halves and find the maximum subarray sum in them recursively. Well, the most tricky part is to handle the case that the maximum subarray may span the two halves. For this case, we use a linear algorithm: starting from the middle element and move to both ends (left and right ends), record the maximum sum we have seen. In this case, the maximum sum is finally equal to the middle element plus the maximum sum of moving leftwards and the maximum sum of moving rightwards.
Well, the code is just a translation of the above idea.
1 class Solution { 2 public: 3 int maxSubArray(vector<int>& nums) { 4 int smax = INT_MIN, n = nums.size(); 5 return maxSub(nums, 0, n - 1, smax); 6 } 7 private: 8 int maxSub(vector<int>& nums, int l, int r, int smax) { 9 if (l > r) return INT_MIN; 10 int m = l + ((r - l) >> 1); 11 int lm = maxSub(nums, l, m - 1, smax); // left half 12 int rm = maxSub(nums, m + 1, r, smax); // right half 13 int i, sum, ml = 0, mr = 0; 14 // Move leftwards 15 for (i = m - 1, sum = 0; i >= l; i--) { 16 sum += nums[i]; 17 ml = max(sum, ml); 18 } 19 // Move rightwards 20 for (i = m + 1, sum = 0; i <= r; i++) { 21 sum += nums[i]; 22 mr = max(sum, mr); 23 } 24 return max(smax, max(ml + mr + nums[m], max(lm, rm))); 25 } 26 };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 2025成都.NET开发者Connect圆满结束
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析