简体   繁体   中英

how does this nested for loop work exactly

function addNum(arr, n) {
    let max = -Infinity
    for(let i = 0; i <= arr.length - n; i++) {
        let temp = 0
        for(let j = 0; j < n; j++) {
            temp += arr[i + j]
        }
        if(temp > max) {
            max = temp
        }
    }
    return max
}

Output : 15

It works

My question how is line 6 working? temp += arr[i + j]. Why isn't it 2+2 = 4 then 2 + 3 = 6? rather it's 2+3 = 5 the 5 + 4 = 9 etc. I thought the whole concept was it will loop n times and keep adding i + j every loop? Sorry if I'm making it hard don't know how to explain

It looks like, you want a subset sum and from this a maximum value.

The subset contains n parts and the nested for loop calculates the sum.

For example, if you have n = 3 and an array of

1 2 3 4 5 6 7 8 9  values
0 1 2 3 4 5 6 7 8  indices i
                   j = 0 ... 2

1 2 3              indices 0 + 0, 0 + 1, 0 + 2
  2 3 4            indices 1 + 0, 1 + 1, 1 + 2
    3 4 5          :
      4 5 6        :
        5 6 7      :
          6 7 8    :
            7 8 9  indices 6 + 0, 6 + 1, 6 + 2

and you get for each row a subset sum for three elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM