-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
// Given an array of numbers, return true if there is a contiguous subarray that sums up to a certain number n. | ||
|
||
// const arr = [1, 2, 3], sum = 5 | ||
// subarraySum(arr, sum) | ||
// // true | ||
|
||
// const arr = [11, 21, 4], sum = 9 | ||
// subarraySum(arr, sum) | ||
// // false | ||
// In the above examples, 2, 3 sum up to 5 so we return true. On the other hand, no subarray in [11, 21, 4] can sum up to 9. | ||
|
||
// solution: https://algodaily.com/challenges/contiguous-subarray-sum | ||
|
||
package main | ||
|
||
func subarraySum(arr []int, sum int) bool { | ||
for i, v := range arr { | ||
if i+1 < len(arr) && v+arr[i+1] == sum { | ||
return true | ||
} | ||
} | ||
|
||
return false | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package main | ||
|
||
import "testing" | ||
|
||
func Test_subarraySum(t *testing.T) { | ||
type args struct { | ||
arr []int | ||
sum int | ||
} | ||
tests := []struct { | ||
name string | ||
args args | ||
want bool | ||
}{ | ||
{ | ||
"`sum` number exists", | ||
args{[]int{1, 2, 3}, 5}, | ||
true, | ||
}, | ||
{ | ||
"`sum` number exists", | ||
args{[]int{1, 2, 3}, 3}, | ||
true, | ||
}, | ||
{ | ||
"`sum` number does not exists", | ||
args{[]int{11, 21, 4}, 5}, | ||
false, | ||
}, | ||
} | ||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
if got := subarraySum(tt.args.arr, tt.args.sum); got != tt.want { | ||
t.Errorf("subarraySum() = %v, want %v", got, tt.want) | ||
} | ||
}) | ||
} | ||
} |