Maximum Subarray and Kadane‘s Algorithm (LeetCode #53)

LeetCode 53. Maximum Subarray

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

subarray is a contiguous part of an array.

To be honest, I have no idea how to solve this problem on my own. I know it has something to do with dynamic programming but I just could not figure out how the state transfer should be implemented. So, I cheated and went to the discussion for answers, and then I found Kadane's algorithm.

It is a rather simple and straightforward algorithm. We first initialize an integer dp array, with dp[i] meaning the maximum sum of a subarray up to the i-th element. To determine what to pass to the array, we simply take the maximum of the following two:

1) the current value in nums, i.e. nums[i]

2) the sum of the current value and the maximum value one element before, i.e. nums[i] + dp[i-1]

To get the maximum value of any subarray, we simply take the maximum in our dp array.


I'll try the explain why the algorithm works:

This algorithm always leaves room for the next element in line, thus allowing the subarray to expand and take in larger elements that are about to come in. But when the next element is too small, i.e. too negative that makes it not worth including it when compared to the element alone, we simply disconnect the subarray. This "discontinuing act" is always true as we would not include subarrays that make our current subarray goes smaller. We are better off starting a new one.

Here's the implementation:

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        // dp array reduced to a single variable
        // as the it only relies one element before it
        int dp = nums[0];

        // stores the maximum value of dp
        int m = dp;

        // loop through the given array
        for(int i = 1; i < nums.size(); i++){
            // transfer of states and finding maximum
            dp = max(nums[i], nums[i] + dp);
            m = max(m, dp);
        }

        // return the maximum value
        return m;
    }
};

P.S. It is only an easy question. It bodes for more practising. TT

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值