How to change the the value of an element inside nested loop?

// find the largest sum of elements in an array, that is divisible by given number n.
fn main() {
    let nums: Vec<u64> = vec![5, 1, 4, 5, 6];

    // Dynamic Programming
    let mut dp: Vec<u64> = vec![0u64; nums.len()];

    let n = 5u64;

    for num in nums {
        for max_sum in dp.iter() {
            let mut max_sum_next = max_sum + i;
            let mut re_next = max_sum_next % n;
            
            if max_sum_next > dp[re_next as usize] {
                dp[re_next as usize] = max_sum_next;
            }
        }
    }

    assert_eq!(20u64, dp[0]);
}

error[E0502]: cannot borrow `dp` as mutable because it is also borrowe
d as immutable
  --> k.rs:13:17
   |
   |         for max_sum in dp.iter() {
   |                        -- immutable borrow occurs here
...
   |                 dp[re_next as usize] = max_sum_next;
   |                 ^^ mutable borrow occurs here
   |             }
   |         }
   |         - immutable borrow ends here

error: aborting due to previous error

I have tried iter() | iter_mut() | into_iter(), but the compiler cannot pass the borrow checker.

Just use a plain indexed loop:

for j in 0 .. dp.len() {
    let max_sum = dp[j];
    ...
1 Like

@vitalyd Thank you, I so stupid :sweat_smile: