"Shortest Subarray with Sum at Least K" hard task No 862 solution failed time complexity
This commit is contained in:
44
862-shortest-subarray-with-sum-at-least-k.go
Normal file
44
862-shortest-subarray-with-sum-at-least-k.go
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
func ShortestSubarray(nums []int, k int) int {
|
||||||
|
if len(nums) == 0 {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
sz := 999999
|
||||||
|
sum := nums[0]
|
||||||
|
carry := 1
|
||||||
|
|
||||||
|
for i := 0; i < len(nums)-1; i++ {
|
||||||
|
if sum >= k {
|
||||||
|
if (carry > 0) && (sz > carry) {
|
||||||
|
sz = carry
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sum = nums[i]
|
||||||
|
for j := i + 1; j < len(nums); j++ {
|
||||||
|
if sum >= k {
|
||||||
|
if sz > (j - i) {
|
||||||
|
sz = j - i
|
||||||
|
}
|
||||||
|
break
|
||||||
|
} else {
|
||||||
|
sum += nums[j]
|
||||||
|
carry = j - i + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if sz == 999999 {
|
||||||
|
if sum >= k {
|
||||||
|
return carry
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sum >= k) && (carry > 0) && (carry < sz) {
|
||||||
|
return carry
|
||||||
|
}
|
||||||
|
|
||||||
|
return sz
|
||||||
|
}
|
||||||
19
862-shortest-subarray-with-sum-at-least-k_test.go
Normal file
19
862-shortest-subarray-with-sum-at-least-k_test.go
Normal file
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user