leetcode------Maximum Subarray

标题: Maximum Subarray
通过率: 34.5%
难度: 中等

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.

本题就是求最大字段和,算法设计的基础算法。动态规划

公式解读:B[i]为到位置i时的最大字段和,A[i]为第i个位置的元素

那么B[k]=max{a[k],B[k-1]+A[k]}

java代码如下:

 1 public class Solution {
 2     public int maxSubArray(int[] A) {
 3         int sum=A[0],tmp=A[0];
 4         for(int i=1;i<A.length;i++){
 5             if(tmp>0){
 6                 tmp+=A[i];
 7             }
 8             else{
 9                 tmp=A[i];
10             }
11             if(tmp>sum){
12                 sum=tmp;
13             }
14         }
15         return sum;
16     }
17 }

python代码如下:

 1 class Solution:
 2     # @param A, a list of integers
 3     # @return an integer
 4     def maxSubArray(self, A):
 5         # kadane's dynamic programming algorithm
 6         maxSum = -1 * (1 << 30)
 7         currSum = maxSum
 8         for a in A:
 9             currSum = max(a, a + currSum)
10             maxSum = max(maxSum, currSum)
11         return maxSum

 

posted @ 2015-02-13 11:25  pku_smile  阅读(155)  评论(0编辑  收藏  举报