Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MARK: - Найти МИНИМАЛЬНЫЙ подотрезок суммой X
- // Решение - префиксная сумма
- // MARK: - Найти МИНИМАЛЬНЫЙ подотрезок суммой X
- func subarraySumXMIN(_ nums: [Int], _ x: Int) -> [Int] {
- var prifix = [0:-1]
- var sum = 0
- var indeces = (start: -1, end: -1)
- var minLength = Int.max
- for r in 0..<nums.count {
- sum += nums[r]
- var prefixToDelete = sum - x
- if prifix[prefixToDelete] != nil {
- // не забывай про +1
- let start = prifix[prefixToDelete]! + 1
- let end = r
- if end - start + 1 < minLength {
- minLength = end - start + 1
- indeces.end = end
- indeces.start = start
- }
- }
- prifix[sum] = r
- }
- return minLength == Int.max ? [-1] : Array(nums[indeces.start...indeces.end])
- }
- //subarraySumXMIN([1,0,5,6, 0, 0, 0, 1, 1, 1, 1, 1, 1,0,0, 1, 1, 1, 1, 1, 3], 11)
- subarraySumXMIN([1,2,3,4,5], 12)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement