Given an unsorted array arr containing only non-negative integers, find a continuous subarray whose sum equals a specified value target.
This algorithm finds a continuous sequence of numbers within a list that adds up to a specific target sum. It does this by examining different 'windows' of numbers within the list and checking if their sum matches the target.
ls = [8, 9, 1, 2, 3, 4, 5, 10, 6, 7] target = 15 output = [] i = 0 while i < len(ls): j = i while j < len(ls): if sum(ls[i:j + 1]) == target: output.append(i) output.append(j) i = len(ls) j += 1 i += 1 print(output)
const list = [8, 9, 1, 2, 3, 4, 5, 10, 6, 7]; const target = 15; const output = []; const sum = (list) => { return list.reduce((acc, val) => acc + val, 0); } for (let i = 0; i < list.length; i++) { for (let j = i; j < list.length; j++) { if (sum(list.slice(i, j + 1)) === target) { output.push(i); output.push(j); i = list.length; } } } console.log(output);