Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,11 @@ tags:

<!-- solution:start -->

### 方法一:枚举 + 后缀和
### 方法一:枚举 + 逆序遍历

我们可以在 $[n - k, n)$ 的范围内枚举终点,然后从终点开始向前遍历,每次累加间隔为 $k$ 的魔法师的能量值,更新答案。

时间复杂度 $O(n)$,其中 $n$ 是数组 `energy` 的长度。空间复杂度 $O(1)$。
时间复杂度 $O(n)$,其中 $n$ 是数组 $\textit{energy}$ 的长度。空间复杂度 $O(1)$。

<!-- tabs:start -->

Expand Down Expand Up @@ -190,6 +190,27 @@ function maximumEnergy(energy: number[], k: number): number {
}
```

#### Rust

```rust
impl Solution {
pub fn maximum_energy(energy: Vec<i32>, k: i32) -> i32 {
let n = energy.len();
let mut ans = i32::MIN;
for i in n - k as usize..n {
let mut s = 0;
let mut j = i as i32;
while j >= 0 {
s += energy[j as usize];
ans = ans.max(s);
j -= k;
}
}
ans
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,11 @@ tags:

<!-- solution:start -->

### Solution 1: Enumeration + Suffix Sum
### Solution 1: Enumeration + Reverse Traversal

We can enumerate the endpoint in the range of $[n - k, n)$, then start from the endpoint and traverse backwards, adding the energy value of the magician at each $k$ interval, and update the answer.
We can enumerate the endpoints within the range $[n - k, n)$, then traverse backwards from each endpoint, accumulating the energy values of wizards at intervals of $k$, and update the answer.

The time complexity is $O(n)$, where $n$ is the length of the array `energy`. The space complexity is $O(1)$.
The time complexity is $O(n)$, where $n$ is the length of array $\textit{energy}$. The space complexity is $O(1)$.

<!-- tabs:start -->

Expand Down Expand Up @@ -191,6 +191,27 @@ function maximumEnergy(energy: number[], k: number): number {
}
```

#### Rust

```rust
impl Solution {
pub fn maximum_energy(energy: Vec<i32>, k: i32) -> i32 {
let n = energy.len();
let mut ans = i32::MIN;
for i in n - k as usize..n {
let mut s = 0;
let mut j = i as i32;
while j >= 0 {
s += energy[j as usize];
ans = ans.max(s);
j -= k;
}
}
ans
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
impl Solution {
pub fn maximum_energy(energy: Vec<i32>, k: i32) -> i32 {
let n = energy.len();
let mut ans = i32::MIN;
for i in n - k as usize..n {
let mut s = 0;
let mut j = i as i32;
while j >= 0 {
s += energy[j as usize];
ans = ans.max(s);
j -= k;
}
}
ans
}
}