leetcode 上兩個關於求子數組最大值

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;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章