2654. 使数组所有元素变成 1 的最少操作次数
This commit is contained in:
parent
93577c7ff2
commit
9648737245
41
src/main.rs
41
src/main.rs
|
|
@ -1,26 +1,39 @@
|
||||||
struct Solution;
|
struct Solution;
|
||||||
|
|
||||||
impl Solution {
|
impl Solution {
|
||||||
pub fn max_operations(s: String) -> i32 {
|
fn gcd_euclid(mut a: i32, mut b: i32) -> i32 {
|
||||||
let s = s.as_bytes();
|
while b != 0 {
|
||||||
let mut ans = 0;
|
let r = a % b;
|
||||||
let mut ones = 0;
|
a = b;
|
||||||
let mut first_zero = false;
|
b = r;
|
||||||
for i in 0..s.len() {
|
}
|
||||||
if s[i] ==b'1' {
|
a
|
||||||
|
}
|
||||||
|
pub fn min_operations(nums: Vec<i32>) -> i32 {
|
||||||
|
let mut ones = 0;
|
||||||
|
for i in 0..nums.len() {
|
||||||
|
if nums[i] == 1 {
|
||||||
ones += 1;
|
ones += 1;
|
||||||
first_zero = true;
|
|
||||||
}
|
}
|
||||||
else {
|
}
|
||||||
if first_zero {
|
if ones > 0 {
|
||||||
ans += ones;
|
return (nums.len() - ones) as i32;
|
||||||
first_zero = false;
|
}
|
||||||
|
for i in 2..=nums.len() {
|
||||||
|
for j in 0..nums.len() - i + 1 {
|
||||||
|
let mut gcd = nums[j];
|
||||||
|
for k in j + 1..j + i {
|
||||||
|
gcd = Self::gcd_euclid(gcd, nums[k]);
|
||||||
|
}
|
||||||
|
if gcd == 1 {
|
||||||
|
return nums.len() as i32 - 1 + i as i32 - 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ans
|
-1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn main() {
|
fn main() {
|
||||||
let result = Solution::max_operations(String::from("1001101"));
|
let result = Solution::min_operations(vec![1,1]);
|
||||||
println!("{:?}", result);
|
println!("{:?}", result);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue