标签:time example red script sample view feedback == complex
Given an array of integers, find a contiguous subarray which has the largest sum.
The subarray should contain at least one number.
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.
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;
}
}
标签:time example red script sample view feedback == complex
原文地址:https://www.cnblogs.com/FLAGyuri/p/12078195.html