【LeetCode】Maximum Subarray

来源:互联网 发布:网络推广网站排名 编辑:程序博客网 时间:2024/06/08 09:03
Maximum Subarray 
Total Accepted: 20964 Total Submissions: 62498 My Submissions
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.
【解题思路】
最大连续子数组和。
初始值tempSum为0,扫描数组,如果tempSum<0,tempSum=A[i],否则就累加。
每次和maxSum比较大小,取最大值。

Java AC 408ms

public class Solution {    public int maxSubArray(int[] A) {        int len = A.length;        if(len == 1){            return A[0];        }        int maxSum = A[0];        int tempSum = 0;        for(int i = 0; i < len ; i++){            if(tempSum < 0){                tempSum = A[i];            }else if(tempSum >= 0){                tempSum += A[i];            }            if(tempSum > maxSum){                maxSum = tempSum;            }        }        return maxSum;    }}

Python AC 300ms

class Solution:    # @param A, a list of integers    # @return an integer    def maxSubArray(self, A):        if A is None or len(A) == 0:            return 0        a_len = len(A)        maxSum = A[0]        tempSum = 0        for i in range(a_len):            if tempSum < 0:                tempSum = A[i]            else:                tempSum += A[i]            if tempSum > maxSum:                maxSum = tempSum        return maxSum



0 0
原创粉丝点击