[leetcode]53. Maximum Subarray(Java)

来源:互联网 发布:设矩阵a可相似对角化 编辑:程序博客网 时间:2024/05/20 11:35

leetcode:https://leetcode.com/problems/maximum-subarray/#/description

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.

click to show more practice.

Java Code:

package go.jacob.day622;/** * [leetcode]53. Maximum Subarray * @author Administrator * */public class Demo2 {/* * 202 / 202 test cases passed. * Status: Accepted * Runtime: 16 ms * tc:O(n) */public int maxSubArray(int[] nums) {if (nums == null || nums.length < 1)return -1;int sum = 0, maxSum = Integer.MIN_VALUE;for (int i = 0; i < nums.length; i++) {sum += nums[i];if (sum > maxSum)maxSum = sum;if (sum <= 0)sum = 0;}return maxSum;}}



原创粉丝点击