Created
October 11, 2020 10:58
-
-
Save SandeepAggarwal/833f54f54dec6b4cfbbd2f9e10b20b65 to your computer and use it in GitHub Desktop.
Given an unsorted array of nonnegative integers, find a continuous subarray which adds to a given number.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import PlaygroundSupport | |
func findSubArrayWhoseCountMatches(targetValue: Int, in array: [Int]) -> [Int] { | |
var sum = 0 | |
var startIndex = 0 | |
for index in 0..<array.count { | |
sum = sum + array[index] | |
while sum > target { | |
sum = sum - array[startIndex] | |
startIndex = startIndex + 1 | |
} | |
if sum == target { | |
return [startIndex, index] | |
} | |
} | |
return [] | |
} | |
let arr = [1, 4, 20, 3, 10, 5] | |
let target = 33 | |
let subArrayIndexes = findSubArrayWhoseCountMatches(targetValue: target, in: arr) | |
print(subArrayIndexes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment