[LeetCode] Maximum Subarray

来源:互联网 发布:浙江c语言二级考试时间 编辑:程序博客网 时间:2024/05/16 02:10

Problem : 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.

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

1.C++版
class Solution {public:    int maxSubArray(int A[], int n) {                int currentSum = 0,greatestSum = 0x80000000;        for(int i=0;i<n;++i){            if(currentSum <= 0){                currentSum = A[i];            }else{                currentSum = currentSum + A[i];            }                        if(greatestSum < currentSum){                greatestSum = currentSum;            }        }                return greatestSum;    }};
2.Java版
public class Solution {    public int maxSubArray(int[] A) {        int currentSum = 0,greatestSum = 0x80000000;        for(int i = 0;i < A.length;++i){            if(currentSum <= 0){                currentSum = A[i];            }else{                currentSum =currentSum + A[i];            }                        if(greatestSum < currentSum){                greatestSum = currentSum;            }        }                return greatestSum;    }}
3.Python版
class Solution:    # @param A, a list of integers    # @return an integer    def maxSubArray(self, A):        currentSum = 0        greatestSum = A[0]                for item in A:            if currentSum < 0:                currentSum = item            else:                currentSum = currentSum + item                            if greatestSum < currentSum:                greatestSum = currentSum                        return greatestSum        


0 0