File tree 5 files changed +68
-0
lines changed
algorithms/MaximumAverageSubarrayI
5 files changed +68
-0
lines changed Original file line number Diff line number Diff line change @@ -175,6 +175,7 @@ All solutions will be accepted!
175
175
| 482| [ License Key Formatting] ( https://leetcode-cn.com/problems/license-key-formatting/description/ ) | [ java/py/js] ( ./algorithms/LicenseKeyFormatting ) | Easy|
176
176
| 720| [ Longest Word In Dictionary] ( https://leetcode-cn.com/problems/longest-word-in-dictionary/description/ ) | [ java/py/js] ( ./algorithms/LongestWordInDictionary ) | Easy|
177
177
| 836| [ Rectangle Overlap] ( https://leetcode-cn.com/problems/rectangle-overlap/description/ ) | [ java/py/js] ( ./algorithms/RectangleOverlap ) | Easy|
178
+ | 643| [ Maximum Average Subarray I] ( https://leetcode-cn.com/problems/maximum-average-subarray-i/description/ ) | [ java/py/js] ( ./algorithms/MaximumAverageSubarrayI ) | Easy|
178
179
179
180
# Database
180
181
| #| Title| Solution| Difficulty|
Original file line number Diff line number Diff line change
1
+ # Maximum Average Subarray I
2
+ This problem is easy to solve
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public double findMaxAverage (int [] nums , int k ) {
3
+ int maxSum = 0 ,
4
+ curSum = 0 ,
5
+ preIndex = -k ;
6
+
7
+ for (int num : nums ) {
8
+ if (preIndex < 0 ) {
9
+ curSum += num ;
10
+ maxSum = curSum ;
11
+ preIndex ++;
12
+ } else {
13
+ curSum += num - nums [preIndex ++];
14
+ maxSum = Math .max (maxSum , curSum );
15
+ }
16
+ }
17
+
18
+ return maxSum * 1.0d / k ;
19
+ }
20
+ }
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[] } nums
3
+ * @param {number } k
4
+ * @return {number }
5
+ */
6
+ var findMaxAverage = function ( nums , k ) {
7
+ let maxSum = 0 ,
8
+ curSum = 0 ,
9
+ preIndex = - k
10
+
11
+ nums . forEach ( num => {
12
+ if ( preIndex < 0 ) {
13
+ curSum += num
14
+ maxSum = curSum
15
+ preIndex ++
16
+ } else {
17
+ curSum += num - nums [ preIndex ++ ]
18
+ maxSum = Math . max ( maxSum , curSum )
19
+ }
20
+ } )
21
+
22
+ return maxSum / k
23
+ } ;
Original file line number Diff line number Diff line change
1
+ class Solution (object ):
2
+ def findMaxAverage (self , nums , k ):
3
+ """
4
+ :type nums: List[int]
5
+ :type k: int
6
+ :rtype: float
7
+ """
8
+ max_sum = None
9
+ cur_sum = 0
10
+ pre_index = None
11
+
12
+ for i in range (len (nums )):
13
+ if i < k :
14
+ cur_sum += nums [i ]
15
+ if i == k - 1 : max_sum = cur_sum
16
+ else :
17
+ pre_index = 0 if pre_index == None else pre_index + 1
18
+ cur_sum += nums [i ] - nums [pre_index ]
19
+ max_sum = max (max_sum , cur_sum )
20
+
21
+ return max_sum * 1.0 / k
22
+
You can’t perform that action at this time.
0 commit comments