1. 53. Maximum Subarray
题意:Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.(即求连续子数组的最大值)
详见:https://leetcode.com/problems/maximum-subarray/
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
最关键为比较出 A[i] 与 maxEndingHere+A[i] 的最大值
class Solution {
public static int maxSubArray(int[] A) {
int maxSoFar=A[0], maxEndingHere=A[0];
for(int i=1;i<A.length;++i){
maxEndingHere = Math.max(A[i], maxEndingHere+A[i]);
maxSoFar = Math.max(maxEndingHere, maxSoFar);
}
return maxSoFar;
}
}
2.643. Maximum Average Subarray I
Given an array consisting of n
integers, find the contiguous subarray of given length k
that has the maximum average value. And you need to output the maximum average value.
题意:给定一个数组,求长度为k的连续子组数组的最大平均值
Input: [1,12,-5,-6,50,3], k = 4 Output: 12.75 Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
class Solution {
public double findMaxAverage(int[] nums, int k) {
int sum = 0;
for(int i=0; i<k; i++){
sum += nums[i];
}
int max = sum;
int count =0;
for(int i=k; i<nums.length; i++){
sum += nums[i]-nums[count++];
max = Math.max(max,sum);
}
return (double)max/k;
}
}