41. Maximum Subarray

41. Maximum Subarray

Description

Given an array of integers, find a contiguous subarray which has the largest sum.
The subarray should contain at least one number.

Example

Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] 
has the largest sum = 6.

Solution

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: A integer indicate the sum of max subarray
     */
    public int maxSubArray(int[] nums) {
        // write your code here
        int MaxSum = nums[0], ThisSum = 0;
        for(int i=0;i<nums.length;i++){
            ThisSum += nums[i];
            if(ThisSum > MaxSum){
                MaxSum = ThisSum;
            }else if(ThisSum < 0){
                ThisSum = 0;
            }
        }
        return MaxSum;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章