Skip to content

Commit 2ddaa4d

Browse files
authored
feat: add rust solution to lc problem: No.2366 (#1547)
1 parent 2c9385d commit 2ddaa4d

File tree

3 files changed

+88
-0
lines changed

3 files changed

+88
-0
lines changed

solution/2300-2399/2366.Minimum Replacements to Sort the Array/README.md

+31
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,37 @@ public:
130130
};
131131
```
132132
133+
### **Rust**
134+
135+
```rust
136+
impl Solution {
137+
#[allow(dead_code)]
138+
pub fn minimum_replacement(nums: Vec<i32>) -> i64 {
139+
if nums.len() == 1 {
140+
return 0;
141+
}
142+
143+
let n = nums.len();
144+
let mut max = *nums.last().unwrap();
145+
let mut ret = 0;
146+
147+
for i in (0..=n - 2).rev() {
148+
if nums[i] <= max {
149+
max = nums[i];
150+
continue;
151+
}
152+
// Otherwise make the substitution
153+
let k = (nums[i] + max - 1) / max;
154+
ret += (k - 1) as i64;
155+
// Update the max value, which should be the minimum among the substitution
156+
max = nums[i] / k;
157+
}
158+
159+
ret
160+
}
161+
}
162+
```
163+
133164
### **Go**
134165

135166
```go

solution/2300-2399/2366.Minimum Replacements to Sort the Array/README_EN.md

+31
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,37 @@ public:
108108
};
109109
```
110110
111+
### **Rust**
112+
113+
```rust
114+
impl Solution {
115+
#[allow(dead_code)]
116+
pub fn minimum_replacement(nums: Vec<i32>) -> i64 {
117+
if nums.len() == 1 {
118+
return 0;
119+
}
120+
121+
let n = nums.len();
122+
let mut max = *nums.last().unwrap();
123+
let mut ret = 0;
124+
125+
for i in (0..=n - 2).rev() {
126+
if nums[i] <= max {
127+
max = nums[i];
128+
continue;
129+
}
130+
// Otherwise make the substitution
131+
let k = (nums[i] + max - 1) / max;
132+
ret += (k - 1) as i64;
133+
// Update the max value, which should be the minimum among the substitution
134+
max = nums[i] / k;
135+
}
136+
137+
ret
138+
}
139+
}
140+
```
141+
111142
### **Go**
112143

113144
```go
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
impl Solution {
2+
#[allow(dead_code)]
3+
pub fn minimum_replacement(nums: Vec<i32>) -> i64 {
4+
if nums.len() == 1 {
5+
return 0;
6+
}
7+
8+
let n = nums.len();
9+
let mut max = *nums.last().unwrap();
10+
let mut ret = 0;
11+
12+
for i in (0..=n - 2).rev() {
13+
if nums[i] <= max {
14+
max = nums[i];
15+
continue;
16+
}
17+
// Otherwise make the substitution
18+
let k = (nums[i] + max - 1) / max;
19+
ret += (k - 1) as i64;
20+
// Update the max value, which should be the minimum among the substitution
21+
max = nums[i] / k;
22+
}
23+
24+
ret
25+
}
26+
}

0 commit comments

Comments
 (0)