EP42-Dynamic Programming2

12/04/2017更新

Practice makes perfect. 古人诚不欺我也。今天无意间回顾了一下这道题,发现当年的思路太混乱了,State transition equation写的也不对。而且代码写得太「野路子」了。
详见:http://www.jianshu.com/p/46ea9e851b41


Yesterday we talked about some basic theories about dynamic programming, honestly I'm still not very confident about that, just got a implicit concept in my mind. Here are some other classic problems about DP, maybe we can grab something from them.

Maximum SubArray

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.

Ok this is another typical Dynamic Programming issue. Like I mentioned yesterday, the most difficult/important part of using DP to solve a problem, is to recognize that this problem can be solved by the idea of DP. So how can we know that it can be solve by DP?
You can see the first number of the array is -2, the second number is 1,then the sum of the subarray consisting of the first 2 numbers is -1 + 2 = -1 , however -1 cannot contribute to the maxSubarray because it will make the sum smaller, so we just discard -1, and just start from scratch: make sum = 0.
The state transition equation is:

Max[i+1]
= Max[i] + A[i+1], if (Max[i] + A[i+1] >0)
= 0 ,if (Max[i] + A[i+1] >0) (it shall not be Max[i])

public int maxSubArray(int[] nums) {
    int sum = nums[0], maxSum = nums[0];
    for (int i = 0; i < nums.length; i++) {
        if (sum < 0) {
            sum = 0;
        }
        sum += nums[i];
        //find a new maxSum which saves the current maximum sum
        maxSum = Math.max(maxSum, sum);
    }
    return maxSum;
}

http://www.tuicool.com/articles/IbiMjaI
http://www.tuicool.com/articles/UzmU7jb

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容