Maximum Subarray
Given an array of integers, find a contiguous subarray which has the largest sum. Notice The subarray should contain at least one number. Example Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6. Challenge Can you do it in time complexity O(n)?
Analyse: For each element in that array, it has two choices: combine with its former or not. The max sum from start to an element is only related to the max sum of its former element. For example, in the given array above, the max sum from -2 to 4 is only related to the max sum from -2 to -3, has no relation to elements after 4.
Therefore, it's a DP problem. The equation is: dp[i] = max(dp[i - 1] + nums[i], nums[i]).
Runtime: 36ms
1 class Solution { 2 public: 3 /** 4 * @param nums: A list of integers 5 * @return: A integer indicate the sum of max subarray 6 */ 7 int maxSubArray(vector<int> nums) { 8 // write your code here 9 if (nums.empty()) return 0; 10 11 int n = nums.size(); 12 vector<int> dp(n, 0); 13 dp[0] = nums[0]; 14 int maxSum = nums[0]; 15 for (int i = 1; i < n; i++) { 16 dp[i] = max(dp[i - 1] + nums[i], nums[i]); 17 maxSum = max(maxSum, dp[i]); 18 } 19 return maxSum; 20 } 21 };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步