leetcode:(53) Maximum Subarray(java)

题目:

   

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

题目描述:

  求一个数组的最大子数组和。

具体思路及代码如下:

package Leetcode_Github;

public class GreedyThought_MaximumSubarray_53_1112 {
    public int GreedyThought_MaximumSubarray(int[] nums){
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int preSum = nums[0];
        int maxSum = preSum;
        for (int i = 1; i < nums.length; i++) {
            preSum = preSum < 0 ? nums[i] : preSum + nums[i];
            maxSum = Math.max(preSum, maxSum);
        }
        return maxSum;
    }

    public static void main(String[] args) {
        int[] array = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        GreedyThought_MaximumSubarray_53_1112 test = new GreedyThought_MaximumSubarray_53_1112();
        int result = test.GreedyThought_MaximumSubarray(array);
        System.out.println(result);
    }
}

猜你喜欢

转载自blog.csdn.net/Sunshine_liang1/article/details/83992765