Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add solutions to lc problems: No.0643,1984 #2556

Merged
merged 2 commits into from
Apr 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 54 additions & 24 deletions solution/0600-0699/0643.Maximum Average Subarray I/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,18 @@

## 解法

### 方法一
### 方法一:滑动窗口

我们维护一个长度为 $k$ 的滑动窗口,每次计算窗口内的和 $s$,取最大的和 $s$ 作为答案。

时间复杂度 $O(n)$,其中 $n$ 是数组 $nums$ 的长度。空间复杂度 $O(1)$。

<!-- tabs:start -->

```python
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
s = sum(nums[:k])
ans = s
ans = s = sum(nums[:k])
for i in range(k, len(nums)):
s += nums[i] - nums[i - k]
ans = max(ans, s)
Expand All @@ -75,19 +78,46 @@ class Solution {
}
```

```cpp
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
int s = accumulate(nums.begin(), nums.begin() + k, 0);
int ans = s;
for (int i = k; i < nums.size(); ++i) {
s += nums[i] - nums[i - k];
ans = max(ans, s);
}
return static_cast<double>(ans) / k;
}
};
```

```go
func findMaxAverage(nums []int, k int) float64 {
s := 0
for _, x := range nums[:k] {
s += x
}
ans := s
for i := k; i < len(nums); i++ {
s += nums[i] - nums[i-k]
ans = max(ans, s)
}
return float64(ans) / float64(k)
}
```

```ts
function findMaxAverage(nums: number[], k: number): number {
let n = nums.length;
let ans = 0;
let sum = 0;
// 前k
for (let i = 0; i < k; i++) {
sum += nums[i];
let s = 0;
for (let i = 0; i < k; ++i) {
s += nums[i];
}
ans = sum;
for (let i = k; i < n; i++) {
sum += nums[i] - nums[i - k];
ans = Math.max(ans, sum);
let ans = s;
for (let i = k; i < nums.length; ++i) {
s += nums[i] - nums[i - k];
ans = Math.max(ans, s);
}
return ans / k;
}
Expand All @@ -98,13 +128,13 @@ impl Solution {
pub fn find_max_average(nums: Vec<i32>, k: i32) -> f64 {
let k = k as usize;
let n = nums.len();
let mut sum = nums.iter().take(k).sum::<i32>();
let mut max = sum;
let mut s = nums.iter().take(k).sum::<i32>();
let mut ans = s;
for i in k..n {
sum += nums[i] - nums[i - k];
max = max.max(sum);
s += nums[i] - nums[i - k];
ans = ans.max(s);
}
f64::from(max) / f64::from(k as i32)
f64::from(ans) / f64::from(k as i32)
}
}
```
Expand All @@ -117,16 +147,16 @@ class Solution {
* @return Float
*/
function findMaxAverage($nums, $k) {
$sum = 0;
$s = 0;
for ($i = 0; $i < $k; $i++) {
$sum += $nums[$i];
$s += $nums[$i];
}
$max = $sum;
$ans = $s;
for ($j = $k; $j < count($nums); $j++) {
$sum = $sum - $nums[$j - $k] + $nums[$j];
$max = max($max, $sum);
$s = $s - $nums[$j - $k] + $nums[$j];
$ans = max($ans, $s);
}
return $max / $k;
return $ans / $k;
}
}
```
Expand Down
78 changes: 54 additions & 24 deletions solution/0600-0699/0643.Maximum Average Subarray I/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,18 @@

## Solutions

### Solution 1
### Solution 1: Sliding Window

We maintain a sliding window of length $k$, and for each window, we calculate the sum $s$ of the numbers within the window. We take the maximum sum $s$ as the answer.

The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$.

<!-- tabs:start -->

```python
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
s = sum(nums[:k])
ans = s
ans = s = sum(nums[:k])
for i in range(k, len(nums)):
s += nums[i] - nums[i - k]
ans = max(ans, s)
Expand All @@ -69,19 +72,46 @@ class Solution {
}
```

```cpp
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
int s = accumulate(nums.begin(), nums.begin() + k, 0);
int ans = s;
for (int i = k; i < nums.size(); ++i) {
s += nums[i] - nums[i - k];
ans = max(ans, s);
}
return static_cast<double>(ans) / k;
}
};
```

```go
func findMaxAverage(nums []int, k int) float64 {
s := 0
for _, x := range nums[:k] {
s += x
}
ans := s
for i := k; i < len(nums); i++ {
s += nums[i] - nums[i-k]
ans = max(ans, s)
}
return float64(ans) / float64(k)
}
```

```ts
function findMaxAverage(nums: number[], k: number): number {
let n = nums.length;
let ans = 0;
let sum = 0;
// 前k
for (let i = 0; i < k; i++) {
sum += nums[i];
let s = 0;
for (let i = 0; i < k; ++i) {
s += nums[i];
}
ans = sum;
for (let i = k; i < n; i++) {
sum += nums[i] - nums[i - k];
ans = Math.max(ans, sum);
let ans = s;
for (let i = k; i < nums.length; ++i) {
s += nums[i] - nums[i - k];
ans = Math.max(ans, s);
}
return ans / k;
}
Expand All @@ -92,13 +122,13 @@ impl Solution {
pub fn find_max_average(nums: Vec<i32>, k: i32) -> f64 {
let k = k as usize;
let n = nums.len();
let mut sum = nums.iter().take(k).sum::<i32>();
let mut max = sum;
let mut s = nums.iter().take(k).sum::<i32>();
let mut ans = s;
for i in k..n {
sum += nums[i] - nums[i - k];
max = max.max(sum);
s += nums[i] - nums[i - k];
ans = ans.max(s);
}
f64::from(max) / f64::from(k as i32)
f64::from(ans) / f64::from(k as i32)
}
}
```
Expand All @@ -111,16 +141,16 @@ class Solution {
* @return Float
*/
function findMaxAverage($nums, $k) {
$sum = 0;
$s = 0;
for ($i = 0; $i < $k; $i++) {
$sum += $nums[$i];
$s += $nums[$i];
}
$max = $sum;
$ans = $s;
for ($j = $k; $j < count($nums); $j++) {
$sum = $sum - $nums[$j - $k] + $nums[$j];
$max = max($max, $sum);
$s = $s - $nums[$j - $k] + $nums[$j];
$ans = max($ans, $s);
}
return $max / $k;
return $ans / $k;
}
}
```
Expand Down
12 changes: 12 additions & 0 deletions solution/0600-0699/0643.Maximum Average Subarray I/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
int s = accumulate(nums.begin(), nums.begin() + k, 0);
int ans = s;
for (int i = k; i < nums.size(); ++i) {
s += nums[i] - nums[i - k];
ans = max(ans, s);
}
return static_cast<double>(ans) / k;
}
};
12 changes: 12 additions & 0 deletions solution/0600-0699/0643.Maximum Average Subarray I/Solution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
func findMaxAverage(nums []int, k int) float64 {
s := 0
for _, x := range nums[:k] {
s += x
}
ans := s
for i := k; i < len(nums); i++ {
s += nums[i] - nums[i-k]
ans = max(ans, s)
}
return float64(ans) / float64(k)
}
12 changes: 6 additions & 6 deletions solution/0600-0699/0643.Maximum Average Subarray I/Solution.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ class Solution {
* @return Float
*/
function findMaxAverage($nums, $k) {
$sum = 0;
$s = 0;
for ($i = 0; $i < $k; $i++) {
$sum += $nums[$i];
$s += $nums[$i];
}
$max = $sum;
$ans = $s;
for ($j = $k; $j < count($nums); $j++) {
$sum = $sum - $nums[$j - $k] + $nums[$j];
$max = max($max, $sum);
$s = $s - $nums[$j - $k] + $nums[$j];
$ans = max($ans, $s);
}
return $max / $k;
return $ans / $k;
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
s = sum(nums[:k])
ans = s
ans = s = sum(nums[:k])
for i in range(k, len(nums)):
s += nums[i] - nums[i - k]
ans = max(ans, s)
Expand Down
10 changes: 5 additions & 5 deletions solution/0600-0699/0643.Maximum Average Subarray I/Solution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ impl Solution {
pub fn find_max_average(nums: Vec<i32>, k: i32) -> f64 {
let k = k as usize;
let n = nums.len();
let mut sum = nums.iter().take(k).sum::<i32>();
let mut max = sum;
let mut s = nums.iter().take(k).sum::<i32>();
let mut ans = s;
for i in k..n {
sum += nums[i] - nums[i - k];
max = max.max(sum);
s += nums[i] - nums[i - k];
ans = ans.max(s);
}
f64::from(max) / f64::from(k as i32)
f64::from(ans) / f64::from(k as i32)
}
}
17 changes: 7 additions & 10 deletions solution/0600-0699/0643.Maximum Average Subarray I/Solution.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
function findMaxAverage(nums: number[], k: number): number {
let n = nums.length;
let ans = 0;
let sum = 0;
// 前k
for (let i = 0; i < k; i++) {
sum += nums[i];
let s = 0;
for (let i = 0; i < k; ++i) {
s += nums[i];
}
ans = sum;
for (let i = k; i < n; i++) {
sum += nums[i] - nums[i - k];
ans = Math.max(ans, sum);
let ans = s;
for (let i = k; i < nums.length; ++i) {
s += nums[i] - nums[i - k];
ans = Math.max(ans, s);
}
return ans / k;
}
36 changes: 35 additions & 1 deletion solution/0600-0699/0644.Maximum Average Subarray II/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,41 @@ Note that we do not consider the subarrays of length &lt; 4.

## Solutions

### Solution 1
### Solution 1: Binary Search

We note that if the average value of a subarray with length greater than or equal to $k$ is $v$, then the maximum average number must be greater than or equal to $v$, otherwise the maximum average number must be less than $v$. Therefore, we can use binary search to find the maximum average number.

What are the left and right boundaries of binary search? The left boundary $l$ must be the minimum value in the array, and the right boundary $r$ is the maximum value in the array. Next, we binary search the midpoint $mid$, and judge whether there exists a subarray with length greater than or equal to $k$ whose average value is greater than or equal to $mid$. If it exists, then we update the left boundary $l$ to $mid$, otherwise we update the right boundary $r$ to $mid$. When the difference between the left and right boundaries is less than a very small non-negative number, i.e., $r - l < \epsilon$, we can get the maximum average number, where $\epsilon$ represents a very small positive number, which can be $10^{-5}$.

The key to the problem is how to judge whether the average value of a subarray with length greater than or equal to $k$ is greater than or equal to $v$.

We assume that in the array $nums$, there is a subarray with length $j$, the elements are $a_1, a_2, \cdots, a_j$, and its average value is greater than or equal to $v$, i.e.,

$$
\frac{a_1 + a_2 + \cdots + a_j}{j} \geq v
$$

Then,

$$
a_1 + a_2 + \cdots + a_j \geq v \times j
$$

That is,

$$
(a_1 - v) + (a_2 - v) + \cdots + (a_j - v) \geq 0
$$

We can find that if we subtract $v$ from each element in the array $nums$, the original problem is transformed into a problem of whether the sum of the elements of a subarray with length greater than or equal to $k$ is greater than or equal to $0$. We can use a sliding window to solve this problem.

First, we calculate the sum $s$ of the differences between the first $k$ elements and $v$. If $s \geq 0$, it means that there exists a subarray with length greater than or equal to $k$ whose element sum is greater than or equal to $0$.

Otherwise, we continue to traverse the element $nums[j]$. Suppose the current sum of the differences between the first $j$ elements and $v$ is $s_j$. Then we can maintain the minimum value $mi$ of the sum of the differences between the prefix sum and $v$ in the range $[0,..j-k]$. If $s_j \geq mi$ exists, it means that there exists a subarray with length greater than or equal to $k$ whose element sum is greater than or equal to $0$, and we return $true$.

Otherwise, we continue to traverse the element $nums[j]$ until the entire array is traversed.

The time complexity is $O(n \times \log M)$, where $n$ and $M$ are the length of the array $nums$ and the difference between the maximum and minimum values in the array, respectively. The space complexity is $O(1)$.

<!-- tabs:start -->

Expand Down
Loading
Loading