Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,28 +1,37 @@
# [3397.Maximum Number of Distinct Elements After Operations][title]

> [!WARNING|style:flat]
> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm)

## Description
You are given an integer array `nums` and an integer `k`.

You are allowed to perform the following **operation** on each element of the array **at most** once:

- Add an integer in the range `[-k, k]` to the element.

Return the **maximum** possible number of **distinct** elements in `nums` after performing the **operations**.

**Example 1:**

```
Input: a = "11", b = "1"
Output: "100"
```
Input: nums = [1,2,2,3,3,4], k = 2

## 题意
> ...
Output: 6

## 题解
Explanation:

### 思路1
> ...
Maximum Number of Distinct Elements After Operations
```go
nums changes to [-1, 0, 1, 2, 3, 4] after performing operations on the first four elements.
```

**Example 2:**

```
Input: nums = [4,4,4,4], k = 1

Output: 3

Explanation:

By adding -1 to nums[0] and 1 to nums[1], nums changes to [3, 5, 4, 4].
```

## 结语

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
package Solution

func Solution(x bool) bool {
return x
import (
"math"
"sort"
)

func Solution(nums []int, k int) int {
sort.Ints(nums)
cnt := 0
prev := math.MinInt32

for _, num := range nums {
curr := min(max(num-k, prev+1), num+k)
if curr > prev {
cnt++
prev = curr
}
}
return cnt
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,30 @@ func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs bool
expect bool
inputs []int
k int
expect int
}{
{"TestCase", true, true},
{"TestCase", true, true},
{"TestCase", false, false},
{"TestCase1", []int{1, 2, 2, 3, 3, 4}, 2, 6},
{"TestCase2", []int{4, 4, 4, 4}, 1, 3},
}

// 开始测试
for i, c := range cases {
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
got := Solution(c.inputs)
got := Solution(c.inputs, c.k)
if !reflect.DeepEqual(got, c.expect) {
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
c.expect, got, c.inputs)
t.Fatalf("expected: %v, but got: %v, with inputs: %v %v",
c.expect, got, c.inputs, c.k)
}
})
}
}

//压力测试
// 压力测试
func BenchmarkSolution(b *testing.B) {
}

//使用案列
// 使用案列
func ExampleSolution() {
}
Loading