-
Notifications
You must be signed in to change notification settings - Fork 32
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
3 changed files
with
45 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
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,13 @@ | ||
package day224 | ||
|
||
// SmallestPositiveIntNotInSubsetSum returns the | ||
// smallest positive integer that is not the sum of a subset of the array, | ||
// given a sorted array. | ||
// Runs in O(N) time and O(1) space. | ||
func SmallestPositiveIntNotInSubsetSum(nums []int) int { | ||
result := 1 | ||
for i := 0; i < len(nums) && nums[i] <= result; i++ { | ||
result += nums[i] | ||
} | ||
return result | ||
} |
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,31 @@ | ||
package day224 | ||
|
||
import "testing" | ||
|
||
var testcases = []struct { | ||
nums []int | ||
smallest int | ||
}{ | ||
{[]int{1, 2, 3, 10}, 7}, | ||
{[]int{1, 3, 4, 5}, 2}, | ||
{[]int{1, 2, 6, 10, 11, 15}, 4}, | ||
{[]int{1, 1, 1, 1}, 5}, | ||
{[]int{1, 1, 3, 4}, 10}, | ||
} | ||
|
||
func TestSmallestPositiveIntNotInSubsetSum(t *testing.T) { | ||
t.Parallel() | ||
for _, tc := range testcases { | ||
if result := SmallestPositiveIntNotInSubsetSum(tc.nums); result != tc.smallest { | ||
t.Errorf("For %v, expected %v, got %v", tc.nums, tc.smallest, result) | ||
} | ||
} | ||
} | ||
|
||
func BenchmarkSmallestPositiveIntNotInSubsetSum(b *testing.B) { | ||
for i := 0; i < b.N; i++ { | ||
for _, tc := range testcases { | ||
SmallestPositiveIntNotInSubsetSum(tc.nums) | ||
} | ||
} | ||
} |