Skip to content

Commit

Permalink
Merge cc2cdce into 54f0da8
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Dec 17, 2019
2 parents 54f0da8 + cc2cdce commit 521dde9
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -385,4 +385,5 @@ problems from
* [Day 390](https://github.com/vaskoz/dailycodingproblem-go/issues/783)
* [Day 391](https://github.com/vaskoz/dailycodingproblem-go/issues/785)
* [Day 392](https://github.com/vaskoz/dailycodingproblem-go/issues/787)
* [Day 393](https://github.com/vaskoz/dailycodingproblem-go/issues/789)

40 changes: 40 additions & 0 deletions day393/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package day393

// LargestRangeBrute returns the largest range of integers
// using brute force.
// Runtime is O(N*K) where K is the length of the longest range.
// Effectively, this is O(N^2).
// Converts the input into a hash set.
func LargestRangeBrute(nums []int) (int, int) {
if n := len(nums); n == 0 {
return 0, 0
} else if n == 1 {
return nums[0], nums[0]
}

set := make(map[int]struct{}, len(nums))

for _, num := range nums {
set[num] = struct{}{}
}

var longest, sAns, eAns int

for start := range set {
count := 1
ptr := start + 1

for _, found := set[ptr]; found; _, found = set[ptr] {
count++
ptr++
}

if count > longest || (count == longest && start < sAns) {
longest = count
sAns = start
eAns = ptr - 1
}
}

return sAns, eAns
}
33 changes: 33 additions & 0 deletions day393/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package day393

import "testing"

// nolint
var testcases = []struct {
nums []int
start, end int
}{
{[]int{9, 6, 1, 3, 8, 10, 12, 11}, 8, 12},
{[]int{}, 0, 0},
{nil, 0, 0},
{[]int{12}, 12, 12},
{[]int{9, 1, 3, 8, 10, 12, 11, 2, 4, 5}, 1, 5},
}

func TestLargestRangeBrute(t *testing.T) {
t.Parallel()

for _, tc := range testcases {
if s, e := LargestRangeBrute(tc.nums); s != tc.start || e != tc.end {
t.Errorf("Expected (%v,%v), got (%v,%v)", tc.start, tc.end, s, e)
}
}
}

func BenchmarkLargestRangeBrute(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
LargestRangeBrute(tc.nums)
}
}
}

0 comments on commit 521dde9

Please sign in to comment.