【LeetCode】53. Maximum Subarray

53. Maximum Subarray

Description:
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Difficulty:Easy
Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

方法1:Dynamic Programming
  • Time complexity : O ( n ) O\left ( n \right ) O(n)
  • Space complexity : O ( 1 ) O\left ( 1 \right ) O(1)
    思路:
    回忆一下动态规划的四个步骤:
    1、描述优解的结构特征。
    2、递归地定义一个最优解的值。
    3、自底向上计算一个最优解的值。
    4、从已计算的信息中构造一个最优解。
    核心是找到子问题的结构
    如果将子问题分解成maxSubArray(int A[], int i, int j),很难找到子问题和原问题的关系
    换个分解方式maxSubArray(int A[], int i),子问题和原问题的关系如下
    maxSubArray(A, i) = maxSubArray(A, i - 1) > 0 ? maxSubArray(A, i - 1) : 0 + A[i];
// 第一版, 写的不优雅,比较烂
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
		int max_sum = INT_MIN;
		int temp_sum = 0;
		for (int i = 0; i < nums.size(); i++) {
			temp_sum += nums[i];
			if (temp_sum > max_sum)
				max_sum = temp_sum;
			if (temp_sum <= 0)
				temp_sum = 0;
		}
		return max_sum;
    }
};
// 第二版, 优化版
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
		int max_sum = INT_MIN;
		int temp_sum = 0;
		for (int i = 0; i < nums.size(); i++) {
			temp_sum = nums[i] + (temp_sum > 0 ? temp_sum : 0);
		    max_sum = max(max_sum, temp_sum);
		}
		return max_sum;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值