Skip to content

Create 0740-delete-and-earn.go #2126

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 23, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions go/0740-delete-and-earn.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
func deleteAndEarn(nums []int) int {
count := make(map[int]int)

unique := make([]int, 0)

for _, num := range nums {
if _, ok := count[num]; !ok {
unique = append(unique, num)
}

count[num]++
}

sort.Ints(unique)

earn1, earn2 := 0, 0

for i := 0; i < len(unique); i++ {
currEarn := unique[i] * count[unique[i]]

if i > 0 && unique[i] == unique[i - 1] + 1 {
temp := earn2
earn2 = max(earn2, currEarn + earn1)
earn1 = temp
} else {
temp := earn2
earn2 = currEarn + earn2
earn1 = temp
}
}

return earn2
}

func max(a, b int) int {
if a > b {
return a
}

return b
}