This is Lintcode's title: http://www.lintcode.com/zh-cn/problem/subarray-sum-closest/
Give an array and K, find a sub-array, and nearest k, if there are multiple returns to any one.
Of course n squared can be solved, but extra space can be onlogn.
The idea is to use the S (i)-S (j) approach.
First calculate all the S (i), then deposit Map,key is the position of the last element Sum,value.
Then the sum is sorted, and then the sum is traversed once, it is only necessary to determine the two sum of sums before and after the only difference can be found closest to K.
Here's The Go code:
Package main
Import (
"FMT"
"Sort"
)
type P struct{
sum, index int
}
type PList []*p
func (List PList) len () int{
return len (list)
}
func (list PList) less (i, J int) bool{
return list [I].sum < List[j].sum
}
func (list PList) Swap (i, J int) {
list[i], list[j] = List[j], list[i]
}
func ABS (x int) int{
if x >= 0{
return x
}
return-x
}
func subarraysum (Nums []int, K int) (int, int) {
sum: = 0
list: = plist{}
P: = new (p)
p.sum = 0
p.index = 1
list=append (l IST, p) for
i,v: = range nums{
sum + = v
p: = new (p)
p.sum = sum
p.index = i
list=append (list , p)
}
sort. Sort (list)
min, F, b:= 1000000, 0, 0 for
i,v: = Range list{
If i==0 {
continue
}
cur: = ABS ( V.SUM-LIST[I-1].SUM-K)
If cur < min{
min = cur
f = list[i-1].index-1
B = List[i].index
}
}
Return f,b
}
func main () {
array: = []int{-3, 1, 1, -3, 5}
K: = 0
F, b: = Subarraysum (array, k)
fmt. Println (f, b)
}