Maximum Subarray
Posted flagyuri
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
Example1:
Input: [−2,2,−3,4,−1,2,1,−5,3]
Output: 6
Explanation: the contiguous subarray [4,−1,2,1] has the largest sum = 6.
Example2:
Input: [1,2,3,4]
Output: 10
Explanation: the contiguous subarray [1,2,3,4] has the largest sum = 10.
Challenge
Can you do it in time complexity O(n)?
思路:使用前缀和。
public class Solution { /** * @param nums: A list of integers * @return: A integer indicate the sum of max subarray */ public int maxSubArray(int[] A) { if (A == null || A.length == 0){ return 0; } //max记录全局最大值,sum记录前i个数的和,minSum记录前i个数中0-k的最小值 int max = Integer.MIN_VALUE, sum = 0, minSum = 0; for (int i = 0; i < A.length; i++) { sum += A[i]; max = Math.max(max, sum - minSum); minSum = Math.min(minSum, sum); } return max; } }
以上是关于Maximum Subarray的主要内容,如果未能解决你的问题,请参考以下文章