子数组最大累加和问题-java

子数组的最大累加和问题

http://www.nowcoder.com/questionTerminal/554aa508dd5d4fefbf0f86e5fe953abd

import java.util.*;


public class Solution {
    /**
     * max sum of the subarray
     * @param arr int整型一维数组 the array
     * @return int整型
     */
    public int maxsumofSubarray (int[] arr) {

        if(arr.length == 0) {
            return 0;
        }

        int leftBound = 0, rightBound = 0;
        int maxSum = arr[0], tempSum = 0;

        while(rightBound < arr.length) {
            tempSum += arr[rightBound];
            maxSum = tempSum > maxSum ? tempSum : maxSum;
            ++rightBound;

            if(tempSum <= 0) {
                leftBound = rightBound;
            }
        }
        return maxSum;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务