EP42-Dynamic Programming2

12/04/2017更新

Practice makes perfect. 古人誠不欺我也。今天無意間回顧了一下這道題,發現當年的思路太混亂了,State transition equation寫的也不對。而且代碼寫得太「野路子」了。
詳見:http://www.lxweimin.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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容