diff --git a/leetcode/1601-1700/1606.Find-Servers-That-Handled-Most-Number-of-Requests/1.png b/leetcode/1601-1700/1606.Find-Servers-That-Handled-Most-Number-of-Requests/1.png new file mode 100644 index 000000000..ac8524b03 Binary files /dev/null and b/leetcode/1601-1700/1606.Find-Servers-That-Handled-Most-Number-of-Requests/1.png differ diff --git a/leetcode/1601-1700/1606.Find-Servers-That-Handled-Most-Number-of-Requests/README.md b/leetcode/1601-1700/1606.Find-Servers-That-Handled-Most-Number-of-Requests/README.md index f683568fa..e5d6fe639 100755 --- a/leetcode/1601-1700/1606.Find-Servers-That-Handled-Most-Number-of-Requests/README.md +++ b/leetcode/1601-1700/1606.Find-Servers-That-Handled-Most-Number-of-Requests/README.md @@ -1,28 +1,53 @@ # [1606.Find Servers That Handled Most Number of Requests][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 have k servers numbered from `0` to `k-1` that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but **cannot handle more than one request at a time**. The requests are assigned to servers according to a specific algorithm: + +- The `ith` (0-indexed) request arrives. +- If all servers are busy, the request is dropped (not handled at all). +- If the `(i % k)th` server is available, assign the request to that server. +- Otherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the `ith` server is busy, try to assign the request to the `(i+1)th` server, then the `(i+2)th` server, and so on. + +You are given a **strictly increasing** array `arrival` of positive integers, where `arrival[i]` represents the arrival time of the `ith` request, and another array `load`, where `load[i]` represents the load of the `ith` request (the time it takes to complete). Your goal is to find the **busiest server(s)**. A server is considered **busiest** if it handled the most number of requests successfully among all the servers. + +Return a list containing the IDs (0-indexed) of the **busiest server(s)**. You may return the IDs in any order. + +**Example 1:** -**Example 1:** +![1](./1.png) ``` -Input: a = "11", b = "1" -Output: "100" +Input: k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3] +Output: [1] +Explanation: +All of the servers start out available. +The first 3 requests are handled by the first 3 servers in order. +Request 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1. +Request 4 comes in. It cannot be handled since all servers are busy, so it is dropped. +Servers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server. ``` -## 题意 -> ... +**Example 2:** -## 题解 - -### 思路1 -> ... -Find Servers That Handled Most Number of Requests -```go ``` +Input: k = 3, arrival = [1,2,3,4], load = [1,2,1,2] +Output: [0] +Explanation: +The first 3 requests are handled by first 3 servers. +Request 3 comes in. It is handled by server 0 since the server is available. +Server 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server. +``` + +**Example 3:** +``` +Input: k = 3, arrival = [1,2,3,4], load = [1,2,1,2] +Output: [0] +Explanation: +The first 3 requests are handled by first 3 servers. +Request 3 comes in. It is handled by server 0 since the server is available. +Server 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server. +``` ## 结语 diff --git a/leetcode/1601-1700/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Solution.go b/leetcode/1601-1700/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Solution.go index d115ccf5e..23cdffc91 100644 --- a/leetcode/1601-1700/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Solution.go +++ b/leetcode/1601-1700/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Solution.go @@ -1,5 +1,85 @@ package Solution -func Solution(x bool) bool { +import ( + "container/heap" + + "github.com/emirpasic/gods/trees/redblacktree" +) + +type BusyServer struct { + releaseTime int + serverId int +} + +type MinHeap []BusyServer + +func (h MinHeap) Len() int { return len(h) } +func (h MinHeap) Less(i, j int) bool { return h[i].releaseTime < h[j].releaseTime } +func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *MinHeap) Push(x interface{}) { + *h = append(*h, x.(BusyServer)) +} +func (h *MinHeap) Pop() interface{} { + old := *h + n := len(old) + x := old[n-1] + *h = old[0 : n-1] return x } + +func Solution(k int, arrival []int, load []int) []int { + available := redblacktree.NewWithIntComparator() + for i := 0; i < k; i++ { + available.Put(i, true) + } + + busyHeap := &MinHeap{} + heap.Init(busyHeap) + + requestCount := make([]int, k) + maxRequests := 0 + + for i := 0; i < len(arrival); i++ { + currTime := arrival[i] + duration := load[i] + + for busyHeap.Len() > 0 && (*busyHeap)[0].releaseTime <= currTime { + item := heap.Pop(busyHeap).(BusyServer) + available.Put(item.serverId, true) + } + + if available.Size() == 0 { + continue + } + + target := i % k + var serverId int + + node, found := available.Ceiling(target) + if found { + serverId = node.Key.(int) + } else { + serverId = available.Left().Key.(int) + } + + available.Remove(serverId) + heap.Push(busyHeap, BusyServer{ + releaseTime: currTime + duration, + serverId: serverId, + }) + + requestCount[serverId]++ + if requestCount[serverId] > maxRequests { + maxRequests = requestCount[serverId] + } + } + + var result []int + for i := 0; i < k; i++ { + if requestCount[i] == maxRequests { + result = append(result, i) + } + } + + return result +} diff --git a/leetcode/1601-1700/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Solution_test.go b/leetcode/1601-1700/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Solution_test.go index 499883f0b..53b18c41d 100644 --- a/leetcode/1601-1700/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Solution_test.go +++ b/leetcode/1601-1700/1606.Find-Servers-That-Handled-Most-Number-of-Requests/Solution_test.go @@ -9,22 +9,24 @@ import ( func TestSolution(t *testing.T) { // 测试用例 cases := []struct { - name string - inputs bool - expect bool + name string + k int + arrival []int + load []int + expect []int }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", 3, []int{1, 2, 3, 4, 5}, []int{5, 2, 3, 3, 3}, []int{1}}, + {"TestCase2", 3, []int{1, 2, 3, 4}, []int{1, 2, 1, 2}, []int{0}}, + {"TestCase3", 3, []int{1, 2, 3}, []int{10, 12, 11}, []int{0, 1, 2}}, } // 开始测试 for i, c := range cases { t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) { - got := Solution(c.inputs) + got := Solution(c.k, c.arrival, c.load) 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 %v", + c.expect, got, c.k, c.arrival, c.load) } }) } diff --git a/leetcode/2101-2200/2124.Check-if-All-As-Appears-Before-All-Bs/README.md b/leetcode/2101-2200/2124.Check-if-All-As-Appears-Before-All-Bs/README.md index f5429f1e0..16ffc1568 100755 --- a/leetcode/2101-2200/2124.Check-if-All-As-Appears-Before-All-Bs/README.md +++ b/leetcode/2101-2200/2124.Check-if-All-As-Appears-Before-All-Bs/README.md @@ -1,28 +1,37 @@ # [2124.Check if All A's Appears Before All B's][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 +Given a string `s` consisting of **only** the characters `'a'` and `'b'`, return `true` if **every** `'a'` appears before **every** `'b'` in the string. Otherwise, return `false`. + **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" +Input: s = "aaabbb" +Output: true +Explanation: +The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5. +Hence, every 'a' appears before every 'b' and we return true. ``` -## 题意 -> ... +**Example 2:** -## 题解 - -### 思路1 -> ... -Check if All A's Appears Before All B's -```go +``` +Input: s = "abab" +Output: false +Explanation: +There is an 'a' at index 2 and a 'b' at index 1. +Hence, not every 'a' appears before every 'b' and we return false. ``` +**Example 3:** + +``` +Input: s = "bbb" +Output: true +Explanation: +There are no 'a's, hence, every 'a' appears before every 'b' and we return true. +``` ## 结语 diff --git a/leetcode/2101-2200/2124.Check-if-All-As-Appears-Before-All-Bs/Solution.go b/leetcode/2101-2200/2124.Check-if-All-As-Appears-Before-All-Bs/Solution.go index d115ccf5e..201c6e702 100644 --- a/leetcode/2101-2200/2124.Check-if-All-As-Appears-Before-All-Bs/Solution.go +++ b/leetcode/2101-2200/2124.Check-if-All-As-Appears-Before-All-Bs/Solution.go @@ -1,5 +1,13 @@ package Solution -func Solution(x bool) bool { - return x +func Solution(s string) bool { + lastA, earliestB := -1, 1000000007 + for i := range s { + if s[i] == 'a' { + lastA = i + continue + } + earliestB = min(earliestB, i) + } + return lastA < earliestB } diff --git a/leetcode/2101-2200/2124.Check-if-All-As-Appears-Before-All-Bs/Solution_test.go b/leetcode/2101-2200/2124.Check-if-All-As-Appears-Before-All-Bs/Solution_test.go index 499883f0b..b04ce1b34 100644 --- a/leetcode/2101-2200/2124.Check-if-All-As-Appears-Before-All-Bs/Solution_test.go +++ b/leetcode/2101-2200/2124.Check-if-All-As-Appears-Before-All-Bs/Solution_test.go @@ -10,12 +10,12 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool + inputs string expect bool }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", "aaabbb", true}, + {"TestCase2", "abab", false}, + {"TestCase3", "bbb", true}, } // 开始测试 diff --git a/leetcode/2201-2300/2243.Calculate-Digit-Sum-of-a-String/README.md b/leetcode/2201-2300/2243.Calculate-Digit-Sum-of-a-String/README.md index 7763d3366..f99a0b591 100755 --- a/leetcode/2201-2300/2243.Calculate-Digit-Sum-of-a-String/README.md +++ b/leetcode/2201-2300/2243.Calculate-Digit-Sum-of-a-String/README.md @@ -1,28 +1,41 @@ # [2243.Calculate Digit Sum of a String][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 a string `s` consisting of digits and an integer `k`. + +A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following: + +- **Divide** `s` into **consecutive groups** of size `k` such that the first `k` characters are in the first group, the next `k` characters are in the second group, and so on. **Note** that the size of the last group can be smaller than `k`. +- **Replace** each group of `s` with a string representing the sum of all its digits. For example, `"346"` is replaced with `"13"` because `3 + 4 + 6 = 13`. +- **Merge** consecutive groups together to form a new string. If the length of the string is greater than `k`, repeat from step `1`. + +Return `s` after all rounds have been completed. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" +Input: s = "11111222223", k = 3 +Output: "135" +Explanation: +- For the first round, we divide s into groups of size 3: "111", "112", "222", and "23". + ​​​​​Then we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5. + So, s becomes "3" + "4" + "6" + "5" = "3465" after the first round. +- For the second round, we divide s into "346" and "5". + Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5. + So, s becomes "13" + "5" = "135" after second round. +Now, s.length <= k, so we return "135" as the answer. ``` -## 题意 -> ... +**Example 2:** -## 题解 - -### 思路1 -> ... -Calculate Digit Sum of a String -```go ``` - +Input: s = "00000000", k = 3 +Output: "000" +Explanation: +We divide s into "000", "000", and "00". +Then we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. +s becomes "0" + "0" + "0" = "000", whose length is equal to k, so we return "000". +``` ## 结语 diff --git a/leetcode/2201-2300/2243.Calculate-Digit-Sum-of-a-String/Solution.go b/leetcode/2201-2300/2243.Calculate-Digit-Sum-of-a-String/Solution.go index d115ccf5e..f86636ae6 100644 --- a/leetcode/2201-2300/2243.Calculate-Digit-Sum-of-a-String/Solution.go +++ b/leetcode/2201-2300/2243.Calculate-Digit-Sum-of-a-String/Solution.go @@ -1,5 +1,33 @@ package Solution -func Solution(x bool) bool { - return x +import ( + "strconv" + "strings" +) + +func Solution(s string, k int) string { + var buf strings.Builder + + replace := func(src string) string { + buf.Reset() + base := 0 + for i := range src { + if i%k == 0 { + if i != 0 { + _new := strconv.Itoa(base) + buf.WriteString(_new) + } + base = 0 + } + base += int(src[i] - '0') + } + _new := strconv.Itoa(base) + buf.WriteString(_new) + return buf.String() + } + + for len(s) > k { + s = replace(s) + } + return s } diff --git a/leetcode/2201-2300/2243.Calculate-Digit-Sum-of-a-String/Solution_test.go b/leetcode/2201-2300/2243.Calculate-Digit-Sum-of-a-String/Solution_test.go index 499883f0b..b4732b8ab 100644 --- a/leetcode/2201-2300/2243.Calculate-Digit-Sum-of-a-String/Solution_test.go +++ b/leetcode/2201-2300/2243.Calculate-Digit-Sum-of-a-String/Solution_test.go @@ -10,21 +10,21 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs string + k int + expect string }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", "11111222223", 3, "135"}, + {"TestCase2", "00000000", 3, "000"}, } // 开始测试 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) } }) } diff --git a/leetcode/2501-2600/2567.Minimum-Score-by-Changing-Two-Elements/README.md b/leetcode/2501-2600/2567.Minimum-Score-by-Changing-Two-Elements/README.md new file mode 100644 index 000000000..1ebdd55a5 --- /dev/null +++ b/leetcode/2501-2600/2567.Minimum-Score-by-Changing-Two-Elements/README.md @@ -0,0 +1,45 @@ +# [2567.Minimum Score by Changing Two Elements][title] + +## Description +You are given an integer array `nums`. + +- The **low** score of `nums` is the **minimum** absolute difference between any two integers. +- The **high** score of `nums` is the **maximum** absolute difference between any two integers. +- The **score** of `nums` is the sum of the **high** and **low** scores. + +Return the **minimum** score after **changing two elements** of `nums`. + +**Example 1:** + +``` +Input: nums = [1,4,7,8,5] + +Output: 3 + +Explanation: + +Change nums[0] and nums[1] to be 6 so that nums becomes [6,6,7,8,5]. +The low score is the minimum absolute difference: |6 - 6| = 0. +The high score is the maximum absolute difference: |8 - 5| = 3. +The sum of high and low score is 3. +``` + +**Example 2:** + +``` +Input: nums = [1,4,3] + +Output: 0 + +Explanation: + +Change nums[1] and nums[2] to 1 so that nums becomes [1,1,1]. +The sum of maximum absolute difference and minimum absolute difference is 0. +``` + +## 结语 + +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-algorithm][me] + +[title]: https://leetcode.com/problems/minimum-score-by-changing-two-elements +[me]: https://github.com/kylesliu/awesome-golang-algorithm diff --git a/leetcode/2501-2600/2567.Minimum-Score-by-Changing-Two-Elements/Solution.go b/leetcode/2501-2600/2567.Minimum-Score-by-Changing-Two-Elements/Solution.go index d115ccf5e..2716ab130 100755 --- a/leetcode/2501-2600/2567.Minimum-Score-by-Changing-Two-Elements/Solution.go +++ b/leetcode/2501-2600/2567.Minimum-Score-by-Changing-Two-Elements/Solution.go @@ -1,5 +1,16 @@ package Solution -func Solution(x bool) bool { - return x +import "sort" + +func Solution(nums []int) int { + // 绝对值最小的 改成相同肯定就是0 + // 绝对值最大的 + // change [0,1], [n-1, n-2], [0, n-1] + n := len(nums) + sort.Ints(nums) + a := nums[n-1] - nums[2] + b := nums[n-2] - nums[1] + c := nums[n-3] - nums[0] + return min(a, b, c) + } diff --git a/leetcode/2501-2600/2567.Minimum-Score-by-Changing-Two-Elements/Solution_test.go b/leetcode/2501-2600/2567.Minimum-Score-by-Changing-Two-Elements/Solution_test.go index 499883f0b..f07833fc4 100755 --- a/leetcode/2501-2600/2567.Minimum-Score-by-Changing-Two-Elements/Solution_test.go +++ b/leetcode/2501-2600/2567.Minimum-Score-by-Changing-Two-Elements/Solution_test.go @@ -10,12 +10,11 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs []int + expect int }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", []int{1, 4, 7, 8, 5}, 3}, + {"TestCase2", []int{1, 4, 3}, 0}, } // 开始测试 diff --git a/leetcode/2901-3000/2911.Minimum-Changes-to-Make-K-Semi-palindromes/README.md b/leetcode/2901-3000/2911.Minimum-Changes-to-Make-K-Semi-palindromes/README.md index 7f0206236..49b4eb559 100755 --- a/leetcode/2901-3000/2911.Minimum-Changes-to-Make-K-Semi-palindromes/README.md +++ b/leetcode/2901-3000/2911.Minimum-Changes-to-Make-K-Semi-palindromes/README.md @@ -1,28 +1,62 @@ # [2911.Minimum Changes to Make K Semi-palindromes][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 +Given a string `s` and an integer `k`, partition `s` into `k` substrings such that the letter changes needed to make each substring a **semi-palindrome** are minimized. + +Return the **minimum** number of letter changes required. + +A **semi-palindrome** is a special type of string that can be divided into palindromes based on a repeating pattern. To check if a string is a semi-palindrome:​ + +1. Choose a positive divisor d of the string's length. d can range from 1 up to, but not including, the string's length. For a string of length 1, it does not have a valid divisor as per this definition, since the only divisor is its length, which is not allowed. +2. For a given divisor d, divide the string into groups where each group contains characters from the string that follow a repeating pattern of length d. Specifically, the first group consists of characters at positions 1, 1 + d, 1 + 2d, and so on; the second group includes characters at positions 2, 2 + d, 2 + 2d, etc. +3. The string is considered a semi-palindrome if each of these groups forms a palindrome. + +Consider the string `"abcabc"`: + +- The length of `"abcabc"` is `6`. Valid divisors are `1`, `2`, and `3`. +- For `d = 1`: The entire string `"abcabc"` forms one group. Not a palindrome. +- For `d = 2`: + + - Group 1 (positions `1, 3, 5`): `"acb"` + - Group 2 (positions `2, 4, 6`): `"bac"` + - Neither group forms a palindrome. + +- For d = 3: + + - Group 1 (positions `1, 4`): `"aa"` + - Group 2 (positions `2, 5`): `"bb"` + - Group 3 (positions `3, 6`): `"cc"` + - All groups form palindromes. Therefore, "abcabc" is a semi-palindrome. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" +Input: s = "abcac", k = 2 + +Output: 1 + +Explanation: Divide s into "ab" and "cac". "cac" is already semi-palindrome. Change "ab" to "aa", it becomes semi-palindrome with d = 1. ``` -## 题意 -> ... +**Example 2:** -## 题解 +``` +Input: s = "abcdef", k = 2 -### 思路1 -> ... -Minimum Changes to Make K Semi-palindromes -```go +Output: 2 + +Explanation: Divide s into substrings "abc" and "def". Each needs one change to become semi-palindrome. ``` +**Example 3:** + +``` +Input: s = "aabbaa", k = 3 + +Output: 0 + +Explanation: Divide s into substrings "aa", "bb" and "aa". All are already semi-palindromes. +``` ## 结语 diff --git a/leetcode/2901-3000/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Solution.go b/leetcode/2901-3000/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Solution.go index d115ccf5e..5af59f422 100644 --- a/leetcode/2901-3000/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Solution.go +++ b/leetcode/2901-3000/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Solution.go @@ -1,5 +1,81 @@ package Solution -func Solution(x bool) bool { - return x +import "math" + +func Solution(s string, k int) int { + n := len(s) + + // 1. 预处理:找出每个长度的所有合法因数 d + divisors := make([][]int, n+1) + for length := 1; length <= n; length++ { + for d := 1; d < length; d++ { + if length%d == 0 { + divisors[length] = append(divisors[length], d) + } + } + } + + // 2. 预处理 g[i][j]:子串 s[i...j] 变成半回文串的最小修改次数 + g := make([][]int, n) + for i := range g { + g[i] = make([]int, n) + for j := range g[i] { + g[i][j] = math.MaxInt32 / 2 + } + } + + for length := 2; length <= n; length++ { + for i := 0; i <= n-length; i++ { + j := i + length - 1 + for _, d := range divisors[length] { + changes := 0 + // 按步长 d 分组,检查每组是否能通过修改变成回文串 + for offset := 0; offset < d; offset++ { + l, r := 0, (length/d)-1 + for l < r { + idx1 := i + offset + l*d + idx2 := i + offset + r*d + if s[idx1] != s[idx2] { + changes++ + } + l++ + r-- + } + } + if changes < g[i][j] { + g[i][j] = changes + } + } + } + } + + // 3. 动态规划:dp[i][j] 表示前 i 个字符划分为 j 个半回文串所需的最小修改次数 + dp := make([][]int, n+1) + for i := range dp { + dp[i] = make([]int, k+1) + for j := range dp[i] { + dp[i][j] = math.MaxInt32 / 2 + } + } + dp[0][0] = 0 + + for i := 1; i <= n; i++ { + for j := 1; j <= k; j++ { + // 前 j-1 个部分至少需要 2 * (j - 1) 个字符,最后一部分至少需要 2 个字符(即 h <= i - 2) + minH := 2 * (j - 1) + if minH > i-2 { + continue + } + for h := minH; h <= i-2; h++ { + if dp[h][j-1] != math.MaxInt32/2 { + cost := dp[h][j-1] + g[h][i-1] + if cost < dp[i][j] { + dp[i][j] = cost + } + } + } + } + } + + return dp[n][k] } diff --git a/leetcode/2901-3000/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Solution_test.go b/leetcode/2901-3000/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Solution_test.go index 499883f0b..04b5b6564 100644 --- a/leetcode/2901-3000/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Solution_test.go +++ b/leetcode/2901-3000/2911.Minimum-Changes-to-Make-K-Semi-palindromes/Solution_test.go @@ -10,21 +10,22 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs string + k int + expect int }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", "abcac", 2, 1}, + {"TestCase2", "abcdef", 2, 2}, + {"TestCase3", "aabbaa", 3, 0}, } // 开始测试 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) } }) } diff --git a/leetcode/3001-3100/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/README.md b/leetcode/3001-3100/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/README.md index 0b105d98d..885303e6f 100755 --- a/leetcode/3001-3100/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/README.md +++ b/leetcode/3001-3100/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/README.md @@ -1,28 +1,31 @@ # [3041.Maximize Consecutive Elements in an Array After Modification][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 a **0-indexed** array `nums` consisting of **positive** integers. + +Initially, you can increase the value of **any** element in the array by **at most 1**. + +After that, you need to select **one or more** elements from the final array such that those elements are **consecutive** when sorted in increasing order. For example, the elements `[3, 4, 5]` are consecutive while `[3, 4, 6]` and `[1, 1, 2, 3]` are not. + +Return the **maximum** number of elements that you can select. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" +Input: nums = [2,1,5,1,1] +Output: 3 +Explanation: We can increase the elements at indices 0 and 3. The resulting array is nums = [3,1,5,2,1]. +We select the elements [3,1,5,2,1] and we sort them to obtain [1,2,3], which are consecutive. +It can be shown that we cannot select more than 3 consecutive elements. ``` -## 题意 -> ... +**Example 2:** -## 题解 - -### 思路1 -> ... -Maximize Consecutive Elements in an Array After Modification -```go ``` - +Input: nums = [1,4,7,10] +Output: 1 +Explanation: The maximum consecutive elements that we can select is 1. +``` ## 结语 diff --git a/leetcode/3001-3100/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Solution.go b/leetcode/3001-3100/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Solution.go index d115ccf5e..338f7b571 100644 --- a/leetcode/3001-3100/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Solution.go +++ b/leetcode/3001-3100/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Solution.go @@ -1,5 +1,41 @@ package Solution -func Solution(x bool) bool { - return x +import "sort" + +func Solution(nums []int) int { + sort.Ints(nums) + + // dp[v] = 只使用已处理过的元素,能得到的“以值 v 结尾”的最长连续段长度 + dp := make(map[int]int, 4) + ans := 0 + + for _, x := range nums { + useX := dp[x-1] + 1 // 决策一:x 保持 x,前面必须结束在 x-1 + useX1 := dp[x] + 1 // 决策二:x 变成 x+1,前面必须结束在 x + + // 两个转移都基于【旧】dp 算完再写回, + // 保证同一个 x 不会既当 x 又当 x+1(+1 只能用一次)。 + if v := dp[x]; useX > v { + dp[x] = useX + } + if v := dp[x+1]; useX1 > v { + dp[x+1] = useX1 + } + + if dp[x] > ans { + ans = dp[x] + } + if dp[x+1] > ans { + ans = dp[x+1] + } + + // 优化:处理完 x 之后,所有键 < x-1 的 dp 永远不会再被访问 + //(之后只会查 x'-1, x', x'+1,而 x' >= x)。map 只会有 ≤4 个键。 + for k := range dp { + if k < x-1 { + delete(dp, k) + } + } + } + return ans } diff --git a/leetcode/3001-3100/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Solution_test.go b/leetcode/3001-3100/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Solution_test.go index 499883f0b..46ce5e50f 100644 --- a/leetcode/3001-3100/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Solution_test.go +++ b/leetcode/3001-3100/3041.Maximize-Consecutive-Elements-in-an-Array-After-Modification/Solution_test.go @@ -10,12 +10,11 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs []int + expect int }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", []int{2, 1, 5, 1, 1}, 3}, + {"TestCase2", []int{1, 4, 7, 10}, 1}, } // 开始测试 diff --git a/leetcode/3301-3400/3309.Maximum-Possible-Number-by-Binary-Concatenation/README.md b/leetcode/3301-3400/3309.Maximum-Possible-Number-by-Binary-Concatenation/README.md index 6ebc10daa..e1a29f576 100755 --- a/leetcode/3301-3400/3309.Maximum-Possible-Number-by-Binary-Concatenation/README.md +++ b/leetcode/3301-3400/3309.Maximum-Possible-Number-by-Binary-Concatenation/README.md @@ -1,28 +1,36 @@ # [3309.Maximum Possible Number by Binary Concatenation][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 array of integers `nums` of size 3. + +Return the **maximum** possible number whose binary representation can be formed by **concatenating** the binary representation of **all** elements in `nums` in some order. + +**Note** that the binary representation of any number does not contain leading zeros. + **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" -``` +Input: nums = [1,2,3] -## 题意 -> ... +Output: 30 -## 题解 +Explanation: -### 思路1 -> ... -Maximum Possible Number by Binary Concatenation -```go +Concatenate the numbers in the order [3, 1, 2] to get the result "11110", which is the binary representation of 30. ``` +**Example 2:** + +``` +Input: nums = [2,8,16] + +Output: 1296 + +Explanation: + +Concatenate the numbers in the order [2, 8, 16] to get the result "10100010000", which is the binary representation of 1296. +``` ## 结语 diff --git a/leetcode/3301-3400/3309.Maximum-Possible-Number-by-Binary-Concatenation/Solution.go b/leetcode/3301-3400/3309.Maximum-Possible-Number-by-Binary-Concatenation/Solution.go index d115ccf5e..0694c81a5 100644 --- a/leetcode/3301-3400/3309.Maximum-Possible-Number-by-Binary-Concatenation/Solution.go +++ b/leetcode/3301-3400/3309.Maximum-Possible-Number-by-Binary-Concatenation/Solution.go @@ -1,5 +1,21 @@ package Solution -func Solution(x bool) bool { - return x +import "math/bits" + +func after(x, y int) bool { + return y< x< [!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 a tree rooted at node 0 that consists of `n` nodes numbered from `0` to `n - 1`. The tree is represented by an array `parent` of size `n`, where `parent[i]` is the parent of node `i`. Since node 0 is the root, `parent[0] == -1`. + +You are also given a string `s` of length `n`, where `s[i]` is the character assigned to node `i`. + +We make the following changes on the tree **one** time **simultaneously** for all nodes `x` from `1` to `n - 1`: + +- Find the **closest** node `y` to node `x` such that `y` is an ancestor of `x`, and `s[x] == s[y]`. +- If node `y` does not exist, do nothing. +- Otherwise, **remove** the edge between `x` and its current parent and make node `y` the new parent of `x` by adding an edge between them. -**Example 1:** +Return an array `answer` of size `n` where `answer[i]` is the **size** of the subtree rooted at node `i` in the **final** tree. + +**Example 1:** + +![1](./1.png) ``` -Input: a = "11", b = "1" -Output: "100" +Input: parent = [-1,0,0,1,1,1], s = "abaabc" + +Output: [6,3,1,1,1,1] + +Explanation: + + +The parent of node 3 will change from node 1 to node 0. ``` -## 题意 -> ... +**Example 2:** -## 题解 +![2](./2.png) -### 思路1 -> ... -Find Subtree Sizes After Changes -```go ``` +Input: parent = [-1,0,4,0,1], s = "abbba" + +Output: [5,2,1,1,1] + +Explanation: +The following changes will happen at the same time: + +The parent of node 4 will change from node 1 to node 0. +The parent of node 2 will change from node 4 to node 1. +``` + ## 结语 如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-algorithm][me] diff --git a/leetcode/3301-3400/3331.Find-Subtree-Sizes-After-Changes/Solution.go b/leetcode/3301-3400/3331.Find-Subtree-Sizes-After-Changes/Solution.go index d115ccf5e..f62b4bc9c 100644 --- a/leetcode/3301-3400/3331.Find-Subtree-Sizes-After-Changes/Solution.go +++ b/leetcode/3301-3400/3331.Find-Subtree-Sizes-After-Changes/Solution.go @@ -1,5 +1,57 @@ package Solution -func Solution(x bool) bool { - return x +func Solution(parent []int, s string) []int { + n := len(parent) + if n == 0 { + return nil + } + + origAdj := make([][]int, n) + for i := 1; i < n; i++ { + p := parent[i] + origAdj[p] = append(origAdj[p], i) + } + + last := [26]int{} + for i := range last { + last[i] = -1 + } + newParent := make([]int, n) + newParent[0] = -1 + var findNewParent func(u int) + findNewParent = func(u int) { + c := s[u] - 'a' + if u > 0 { + if last[c] != -1 { + newParent[u] = last[c] + } else { + newParent[u] = parent[u] + } + } + prev := last[c] + last[c] = u + for _, v := range origAdj[u] { + findNewParent(v) + } + last[c] = prev + } + findNewParent(0) + newAdj := make([][]int, n) + for i := 1; i < n; i++ { + p := newParent[i] + newAdj[p] = append(newAdj[p], i) + } + ans := make([]int, n) + var calcSize func(u int) int + calcSize = func(u int) int { + size := 1 + for _, v := range newAdj[u] { + size += calcSize(v) + } + ans[u] = size + return size + } + + calcSize(0) + return ans } diff --git a/leetcode/3301-3400/3331.Find-Subtree-Sizes-After-Changes/Solution_test.go b/leetcode/3301-3400/3331.Find-Subtree-Sizes-After-Changes/Solution_test.go index 499883f0b..b729e9dab 100644 --- a/leetcode/3301-3400/3331.Find-Subtree-Sizes-After-Changes/Solution_test.go +++ b/leetcode/3301-3400/3331.Find-Subtree-Sizes-After-Changes/Solution_test.go @@ -10,21 +10,21 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs []int + s string + expect []int }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", []int{-1, 0, 0, 1, 1, 1}, "abaabc", []int{6, 3, 1, 1, 1, 1}}, + {"TestCase2", []int{-1, 0, 4, 0, 1}, "abbba", []int{5, 2, 1, 1, 1}}, } // 开始测试 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.s) 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.s) } }) } diff --git a/leetcode/3301-3400/3360.Stone-Removal-Game/README.md b/leetcode/3301-3400/3360.Stone-Removal-Game/README.md index 4fd99960d..b0cb442e8 100755 --- a/leetcode/3301-3400/3360.Stone-Removal-Game/README.md +++ b/leetcode/3301-3400/3360.Stone-Removal-Game/README.md @@ -1,28 +1,39 @@ # [3360.Stone Removal Game][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 +Alice and Bob are playing a game where they take turns removing stones from a pile, with Alice going first. + +- Alice starts by removing **exactly** 10 stones on her first turn. +- For each subsequent turn, each player removes **exactly** 1 fewer stone than the previous opponent. + +The player who cannot make a move loses the game. + +Given a positive integer `n`, return `true` if Alice wins the game and `false` otherwise. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" -``` +Input: n = 12 -## 题意 -> ... +Output: true -## 题解 +Explanation: -### 思路1 -> ... -Stone Removal Game -```go +Alice removes 10 stones on her first turn, leaving 2 stones for Bob. +Bob cannot remove 9 stones, so Alice wins. ``` +**Example 2:** + +``` +Input: n = 1 + +Output: false + +Explanation: + +Alice cannot remove 10 stones, so Alice loses. +``` ## 结语 diff --git a/leetcode/3301-3400/3360.Stone-Removal-Game/Solution.go b/leetcode/3301-3400/3360.Stone-Removal-Game/Solution.go index d115ccf5e..cf907492f 100644 --- a/leetcode/3301-3400/3360.Stone-Removal-Game/Solution.go +++ b/leetcode/3301-3400/3360.Stone-Removal-Game/Solution.go @@ -1,5 +1,12 @@ package Solution -func Solution(x bool) bool { - return x +func Solution(n int) bool { + aliceWin := false + removes := 10 + for n >= removes { + n -= removes + removes-- + aliceWin = !aliceWin + } + return aliceWin } diff --git a/leetcode/3301-3400/3360.Stone-Removal-Game/Solution_test.go b/leetcode/3301-3400/3360.Stone-Removal-Game/Solution_test.go index 499883f0b..fcd409ff5 100644 --- a/leetcode/3301-3400/3360.Stone-Removal-Game/Solution_test.go +++ b/leetcode/3301-3400/3360.Stone-Removal-Game/Solution_test.go @@ -10,12 +10,11 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool + inputs int expect bool }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", 12, true}, + {"TestCase2", 1, false}, } // 开始测试 diff --git a/leetcode/3301-3400/3364.Minimum-Positive-Sum-Subarray-/README.md b/leetcode/3301-3400/3364.Minimum-Positive-Sum-Subarray-/README.md index e999a834f..c1a1f850b 100755 --- a/leetcode/3301-3400/3364.Minimum-Positive-Sum-Subarray-/README.md +++ b/leetcode/3301-3400/3364.Minimum-Positive-Sum-Subarray-/README.md @@ -1,28 +1,53 @@ # [3364.Minimum Positive Sum Subarray ][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 **two** integers `l` and `r`. Your task is to find the **minimum** sum of a **subarray** whose size is between `l` and `r` (inclusive) and whose sum is greater than 0. + +Return the **minimum** sum of such a subarray. If no such subarray exists, return -1. + +A **subarray** is a contiguous **non-empty** sequence of elements within an array. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" +Input: nums = [3, -2, 1, 4], l = 2, r = 3 + +Output: 1 + +Explanation: + +The subarrays of length between l = 2 and r = 3 where the sum is greater than 0 are: + +[3, -2] with a sum of 1 +[1, 4] with a sum of 5 +[3, -2, 1] with a sum of 2 +[-2, 1, 4] with a sum of 3 +Out of these, the subarray [3, -2] has a sum of 1, which is the smallest positive sum. Hence, the answer is 1. +``` + +**Example 2:** + ``` +Input: nums = [-2, 2, -3, 1], l = 2, r = 3 + +Output: -1 + +Explanation: -## 题意 -> ... +There is no subarray of length between l and r that has a sum greater than 0. So, the answer is -1. +``` -## 题解 +**Example 3:** -### 思路1 -> ... -Minimum Positive Sum Subarray -```go ``` +nput: nums = [1, 2, 3, 4], l = 2, r = 4 + +Output: 3 +Explanation: + +The subarray [1, 2] has a length of 2 and the minimum sum greater than 0. So, the answer is 3. +``` ## 结语 diff --git a/leetcode/3301-3400/3364.Minimum-Positive-Sum-Subarray-/Solution.go b/leetcode/3301-3400/3364.Minimum-Positive-Sum-Subarray-/Solution.go index d115ccf5e..92be11398 100644 --- a/leetcode/3301-3400/3364.Minimum-Positive-Sum-Subarray-/Solution.go +++ b/leetcode/3301-3400/3364.Minimum-Positive-Sum-Subarray-/Solution.go @@ -1,5 +1,27 @@ package Solution -func Solution(x bool) bool { - return x +import "math" + +func Solution(nums []int, l int, r int) int { + n := len(nums) + sum := make([]int, n) + sum[0] = nums[0] + for i := 1; i < n; i++ { + sum[i] = sum[i-1] + nums[i] + } + + ret := math.MaxInt + for length := l; length <= r; length++ { + remove := 0 + for e := length - 1; e < n; e++ { + if s := sum[e] - remove; s > 0 { + ret = min(ret, s) + } + remove = sum[e+1-length] + } + } + if ret == math.MaxInt { + return -1 + } + return ret } diff --git a/leetcode/3301-3400/3364.Minimum-Positive-Sum-Subarray-/Solution_test.go b/leetcode/3301-3400/3364.Minimum-Positive-Sum-Subarray-/Solution_test.go index 499883f0b..8653ee508 100644 --- a/leetcode/3301-3400/3364.Minimum-Positive-Sum-Subarray-/Solution_test.go +++ b/leetcode/3301-3400/3364.Minimum-Positive-Sum-Subarray-/Solution_test.go @@ -10,21 +10,22 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs []int + l, r int + expect int }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", []int{3, -2, 1, 4}, 2, 3, 1}, + {"TestCase2", []int{-2, 2, -3, 1}, 2, 3, -1}, + {"TestCase3", []int{1, 2, 3, 4}, 2, 4, 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.l, c.r) 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 %v", + c.expect, got, c.inputs, c.l, c.r) } }) } diff --git a/leetcode/3401-3500/3411.Maximum-Subarray-With-Equal-Products/README.md b/leetcode/3401-3500/3411.Maximum-Subarray-With-Equal-Products/README.md index 74fcaceab..acd0651e0 100755 --- a/leetcode/3401-3500/3411.Maximum-Subarray-With-Equal-Products/README.md +++ b/leetcode/3401-3500/3411.Maximum-Subarray-With-Equal-Products/README.md @@ -1,28 +1,47 @@ # [3411.Maximum Subarray With Equal Products][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 array of **positive** integers `nums`. + +An array arr is called **product equivalent** if `prod(arr) == lcm(arr) * gcd(arr)`, where: + +- `prod(arr)` is the product of all elements of `arr`. +- `gcd(arr)` is the GCD of all elements of `arr`. +- `lcm(arr)` is the LCM of all elements of `arr`. + +Return the length of the **longest product equivalent subarray** of `nums`. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" +Input: nums = [1,2,1,2,1,1,1] + +Output: 5 + +Explanation: + +The longest product equivalent subarray is [1, 2, 1, 1, 1], where prod([1, 2, 1, 1, 1]) = 2, gcd([1, 2, 1, 1, 1]) = 1, and lcm([1, 2, 1, 1, 1]) = 2. +``` + +**Example 2:** + ``` +Input: nums = [2,3,4,5,6] -## 题意 -> ... +Output: 3 -## 题解 +Explanation: -### 思路1 -> ... -Maximum Subarray With Equal Products -```go +The longest product equivalent subarray is [3, 4, 5]. ``` +**Example 3:** + +``` +Input: nums = [1,2,3,1,4,5,1] + +Output: 5 +``` ## 结语 diff --git a/leetcode/3401-3500/3411.Maximum-Subarray-With-Equal-Products/Solution.go b/leetcode/3401-3500/3411.Maximum-Subarray-With-Equal-Products/Solution.go index d115ccf5e..ed58ea860 100644 --- a/leetcode/3401-3500/3411.Maximum-Subarray-With-Equal-Products/Solution.go +++ b/leetcode/3401-3500/3411.Maximum-Subarray-With-Equal-Products/Solution.go @@ -1,5 +1,63 @@ package Solution -func Solution(x bool) bool { - return x +func innerGCD(a, b int64) int64 { + for b != 0 { + a, b = b, a%b + } + return a +} + +func innerLCM(a, b int64) int64 { + g := innerGCD(a, b) + return (a / g) * b +} + +func Solution(nums []int) int { + n := len(nums) + if n == 0 { + return 0 + } + + ret, left := 1, 0 + var prod int64 = 1 + var curGCD, curLCM int64 = 0, 0 + + for right := 0; right < n; right++ { + x := int64(nums[right]) + prod *= x + if right == left { + curGCD = x + curLCM = x + } else { + curGCD = innerGCD(curGCD, x) + curLCM = innerLCM(curLCM, x) + } + + for left <= right && prod > curLCM*curGCD { + prod /= int64(nums[left]) + left++ + if left <= right { + curGCD = int64(nums[left]) + curLCM = int64(nums[left]) + prod = int64(nums[left]) + for k := left + 1; k <= right; k++ { + v := int64(nums[k]) + prod *= v + curGCD = innerGCD(curGCD, v) + curLCM = innerLCM(curLCM, v) + } + } else { + prod = 1 + curGCD, curLCM = 0, 0 + } + } + + // 挪到这里:每次 right 移动(及必要缩窗)后检查当前窗口是否合法 + if curGCD > 0 && prod == curLCM*curGCD { + if length := right - left + 1; length > ret { + ret = length + } + } + } + return ret } diff --git a/leetcode/3401-3500/3411.Maximum-Subarray-With-Equal-Products/Solution_test.go b/leetcode/3401-3500/3411.Maximum-Subarray-With-Equal-Products/Solution_test.go index 499883f0b..b9dec8ab5 100644 --- a/leetcode/3401-3500/3411.Maximum-Subarray-With-Equal-Products/Solution_test.go +++ b/leetcode/3401-3500/3411.Maximum-Subarray-With-Equal-Products/Solution_test.go @@ -10,12 +10,12 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs []int + expect int }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", []int{1, 2, 1, 2, 1, 1, 1}, 5}, + {"TestCase2", []int{2, 3, 4, 5, 6}, 3}, + {"TestCase3", []int{1, 2, 3, 1, 4, 5, 1}, 5}, } // 开始测试 diff --git a/leetcode/3401-3500/3420.Count-Non-Decreasing-Subarrays-After-K-Operations/README.md b/leetcode/3401-3500/3420.Count-Non-Decreasing-Subarrays-After-K-Operations/README.md index 6a642f29c..dbcbf93aa 100755 --- a/leetcode/3401-3500/3420.Count-Non-Decreasing-Subarrays-After-K-Operations/README.md +++ b/leetcode/3401-3500/3420.Count-Non-Decreasing-Subarrays-After-K-Operations/README.md @@ -1,28 +1,39 @@ # [3420.Count Non-Decreasing Subarrays After K 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 array `nums` of `n` integers and an integer `k`. + +For each subarray of `nums`, you can apply **up** to `k` operations on it. In each operation, you increment any element of the subarray by 1. + +**Note** that each subarray is considered independently, meaning changes made to one subarray do not persist to another. + +Return the number of subarrays that you can make **non-decreasing** after performing at most `k` operations. + +An array is said to be **non-decreasing** if each element is greater than or equal to its previous element, if it exists. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" -``` +Input: nums = [6,3,1,2,4,4], k = 7 -## 题意 -> ... +Output: 17 -## 题解 +Explanation: -### 思路1 -> ... -Count Non-Decreasing Subarrays After K Operations -```go +Out of all 21 possible subarrays of nums, only the subarrays [6, 3, 1], [6, 3, 1, 2], [6, 3, 1, 2, 4] and [6, 3, 1, 2, 4, 4] cannot be made non-decreasing after applying up to k = 7 operations. Thus, the number of non-decreasing subarrays is 21 - 4 = 17. ``` +**Example 2:** + +``` +Input: nums = [6,3,1,3,6], k = 4 + +Output: 12 + +Explanation: + +The subarray [3, 1, 3, 6] along with all subarrays of nums with three or fewer elements, except [6, 3, 1], can be made non-decreasing after k operations. There are 5 subarrays of a single element, 4 subarrays of two elements, and 2 subarrays of three elements except [6, 3, 1], so there are 1 + 5 + 4 + 2 = 12 subarrays that can be made non-decreasing. +``` ## 结语 diff --git a/leetcode/3401-3500/3420.Count-Non-Decreasing-Subarrays-After-K-Operations/Solution.go b/leetcode/3401-3500/3420.Count-Non-Decreasing-Subarrays-After-K-Operations/Solution.go index d115ccf5e..b25e85982 100644 --- a/leetcode/3401-3500/3420.Count-Non-Decreasing-Subarrays-After-K-Operations/Solution.go +++ b/leetcode/3401-3500/3420.Count-Non-Decreasing-Subarrays-After-K-Operations/Solution.go @@ -1,5 +1,79 @@ package Solution -func Solution(x bool) bool { +import "container/heap" + +func Solution(nums []int, k int) int64 { + n := len(nums) + var ans int64 = 0 + var operations int64 = 0 + // Maintain the window maximum with a priority queue + h := &MaxHeap{} + heap.Init(h) + // Record the set of elements covered by this index + cnt := make([][]int, n) + for i := range cnt { + cnt[i] = []int{} + } + // Index of the first greater-or-equal element to the right + pos := make([]int, n) + for i := range pos { + pos[i] = n + } + // Decreasing monotonic stack + st := []int{} + + left := 0 + for right := 0; right < n; right++ { + // Maintain the monotonic stack + for len(st) > 0 && nums[right] >= nums[st[len(st)-1]] { + pos[st[len(st)-1]] = right + st = st[:len(st)-1] + } + // The stack top is the nearest greater element to the left of nums[right] + if len(st) > 0 { + cnt[st[len(st)-1]] = append(cnt[st[len(st)-1]], right) + } + st = append(st, right) + + // The priority queue front is the window maximum + heap.Push(h, [2]int{nums[right], right}) + // Adding nums[right] increases the operation count + if diff := (*h)[0][0] - nums[right]; diff > 0 { + operations += int64(diff) + } + + // The minimum operation count exceeds k; shrink the window + for operations > int64(k) { + // Removing nums[left] from the window decreases the operation count + for _, i := range cnt[left] { + // Subtract the contribution + operations -= int64(nums[left]-nums[i]) * int64(min(pos[i], right+1)-i) + } + left++ + } + + // Remove elements with indices less than left from the priority queue + for h.Len() > 0 && (*h)[0][1] < left { + heap.Pop(h) + } + + // There are right - left + 1 valid contiguous subarrays ending at right + ans += int64(right - left + 1) + } + + return ans +} + +type MaxHeap [][2]int + +func (h MaxHeap) Len() int { return len(h) } +func (h MaxHeap) Less(i, j int) bool { return h[i][0] > h[j][0] } +func (h MaxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *MaxHeap) Push(x interface{}) { *h = append(*h, x.([2]int)) } +func (h *MaxHeap) Pop() interface{} { + old := *h + n := len(old) + x := old[n-1] + *h = old[:n-1] return x } diff --git a/leetcode/3401-3500/3420.Count-Non-Decreasing-Subarrays-After-K-Operations/Solution_test.go b/leetcode/3401-3500/3420.Count-Non-Decreasing-Subarrays-After-K-Operations/Solution_test.go index 499883f0b..a2701cff0 100644 --- a/leetcode/3401-3500/3420.Count-Non-Decreasing-Subarrays-After-K-Operations/Solution_test.go +++ b/leetcode/3401-3500/3420.Count-Non-Decreasing-Subarrays-After-K-Operations/Solution_test.go @@ -10,21 +10,21 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs []int + k int + expect int64 }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", []int{6, 3, 1, 2, 4, 4}, 7, 17}, + {"TestCase2", []int{6, 3, 1, 3, 6}, 4, 12}, } // 开始测试 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) } }) } diff --git a/leetcode/3401-3500/3493.Properties-Graph/1.png b/leetcode/3401-3500/3493.Properties-Graph/1.png new file mode 100644 index 000000000..b4a933a42 Binary files /dev/null and b/leetcode/3401-3500/3493.Properties-Graph/1.png differ diff --git a/leetcode/3401-3500/3493.Properties-Graph/2.png b/leetcode/3401-3500/3493.Properties-Graph/2.png new file mode 100644 index 000000000..20d2bea10 Binary files /dev/null and b/leetcode/3401-3500/3493.Properties-Graph/2.png differ diff --git a/leetcode/3401-3500/3493.Properties-Graph/README.md b/leetcode/3401-3500/3493.Properties-Graph/README.md index 0a84bb7b2..d6731e349 100755 --- a/leetcode/3401-3500/3493.Properties-Graph/README.md +++ b/leetcode/3401-3500/3493.Properties-Graph/README.md @@ -1,28 +1,53 @@ # [3493.Properties Graph][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 a 2D integer array `properties` having dimensions `n x m` and an integer `k`. + +Define a function `intersect(a, b)` that returns the **number of distinct integers** common to both arrays `a` and `b`. + +Construct an **undirected** graph where each index `i` corresponds to `properties[i]`. There is an edge between node `i` and node `j` if and only if `intersect(properties[i], properties[j]) >= k`, where `i` and `j` are in the range `[0, n - 1] and i != j`. + +Return the number of **connected components** in the resulting graph. + +**Example 1:** + +![1](./1.png) + +``` +Input: properties = [[1,2],[1,1],[3,4],[4,5],[5,6],[7,7]], k = 1 + +Output: 3 -**Example 1:** +Explanation: +The graph formed has 3 connected components: ``` -Input: a = "11", b = "1" -Output: "100" + +**Example 2:** + +![2](./2.png) + ``` +Input: properties = [[1,2,3],[2,3,4],[4,3,5]], k = 2 -## 题意 -> ... +Output: 1 -## 题解 +Explanation: -### 思路1 -> ... -Properties Graph -```go +The graph formed has 1 connected component: ``` +**Example 3:** + +``` +Input: properties = [[1,1],[1,1]], k = 2 + +Output: 2 + +Explanation: + +intersect(properties[0], properties[1]) = 1, which is less than k. This means there is no edge between properties[0] and properties[1] in the graph. +``` ## 结语 diff --git a/leetcode/3401-3500/3493.Properties-Graph/Solution.go b/leetcode/3401-3500/3493.Properties-Graph/Solution.go index d115ccf5e..2ba627592 100644 --- a/leetcode/3401-3500/3493.Properties-Graph/Solution.go +++ b/leetcode/3401-3500/3493.Properties-Graph/Solution.go @@ -1,5 +1,63 @@ package Solution -func Solution(x bool) bool { - return x +type unionFind3493 struct { + father [101]int +} + +func (u *unionFind3493) find(x int) int { + if u.father[x] != x { + u.father[x] = u.find(u.father[x]) + } + return u.father[x] +} + +func (u *unionFind3493) union(x, y int) { + fx := u.find(x) + fy := u.find(y) + if fx < fy { + u.father[fy] = fx + } else { + u.father[fx] = fy + } +} + +func Solution(properties [][]int, k int) int { + n := len(properties) + intersect := func(a, b [101]bool) int { + cnt := 0 + for i := range 101 { + if a[i] && b[i] { + cnt++ + } + } + return cnt + } + + distinctNumArr := make([][101]bool, n) + for i := range properties { + for _, elem := range properties[i] { + distinctNumArr[i][elem] = true + } + } + + u := &unionFind3493{} + for i := range 101 { + u.father[i] = i + } + for i := range n { + for j := i + 1; j < n; j++ { + if intersect(distinctNumArr[i], distinctNumArr[j]) >= k { + u.union(i, j) + } + } + } + + var f int + components := make(map[int]struct{}, n) + for i := range n { + f = u.find(i) + components[f] = struct{}{} + + } + return len(components) } diff --git a/leetcode/3401-3500/3493.Properties-Graph/Solution_test.go b/leetcode/3401-3500/3493.Properties-Graph/Solution_test.go index 499883f0b..1f47960d7 100644 --- a/leetcode/3401-3500/3493.Properties-Graph/Solution_test.go +++ b/leetcode/3401-3500/3493.Properties-Graph/Solution_test.go @@ -10,21 +10,22 @@ 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}, {1, 1}, {3, 4}, {4, 5}, {5, 6}, {7, 7}}, 1, 3}, + {"TestCase2", [][]int{{1, 2, 3}, {2, 3, 4}, {4, 3, 5}}, 2, 1}, + {"TestCase3", [][]int{{1, 1}, {1, 1}}, 2, 2}, } // 开始测试 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) } }) } diff --git a/leetcode/3701-3800/3789.Minimum-Cost-to-Acquire-Required-Items/README.md b/leetcode/3701-3800/3789.Minimum-Cost-to-Acquire-Required-Items/README.md index f95c1d933..506ac403e 100755 --- a/leetcode/3701-3800/3789.Minimum-Cost-to-Acquire-Required-Items/README.md +++ b/leetcode/3701-3800/3789.Minimum-Cost-to-Acquire-Required-Items/README.md @@ -1,28 +1,55 @@ # [3789.Minimum Cost to Acquire Required Items][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 five integers `cost1`, `cost2`, `costBoth`, `need1`, and `need2`. + +There are three types of items available: + +- An item of **type 1** costs `cost1` and contributes 1 unit to the type 1 requirement only. +- An item of **type 2** costs `cost2` and contributes 1 unit to the type 2 requirement only. +- An item of **type 3** costs `costBoth` and contributes 1 unit to **both** type 1 and type 2 requirements. + +You must collect enough items so that the total contribution toward type 1 is **at least** `need1` and the total contribution toward type 2 is **at least** `need2`. + +Return an integer representing the **minimum** possible total cost to achieve these requirements. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" +Input: cost1 = 3, cost2 = 2, costBoth = 1, need1 = 3, need2 = 2 + +Output: 3 + +Explanation: + +After buying three type 3 items, which cost 3 * 1 = 3, the total contribution to type 1 is 3 (>= need1 = 3) and to type 2 is 3 (>= need2 = 2). +Any other valid combination would cost more, so the minimum total cost is 3. ``` -## 题意 -> ... +**Example 2:** -## 题解 +``` +Input: cost1 = 5, cost2 = 4, costBoth = 15, need1 = 2, need2 = 3 + +Output: 22 + +Explanation: + +We buy need1 = 2 items of type 1 and need2 = 3 items of type 2: 2 * 5 + 3 * 4 = 10 + 12 = 22. +Any other valid combination would cost more, so the minimum total cost is 22. +``` + +**Example 3:** -### 思路1 -> ... -Minimum Cost to Acquire Required Items -```go ``` +Input: cost1 = 5, cost2 = 4, costBoth = 15, need1 = 0, need2 = 0 + +Output: 0 +Explanation: + +Since no items are required (need1 = need2 = 0), we buy nothing and pay 0. +``` ## 结语 diff --git a/leetcode/3701-3800/3789.Minimum-Cost-to-Acquire-Required-Items/Solution.go b/leetcode/3701-3800/3789.Minimum-Cost-to-Acquire-Required-Items/Solution.go index d115ccf5e..340e61afd 100644 --- a/leetcode/3701-3800/3789.Minimum-Cost-to-Acquire-Required-Items/Solution.go +++ b/leetcode/3701-3800/3789.Minimum-Cost-to-Acquire-Required-Items/Solution.go @@ -1,5 +1,24 @@ package Solution -func Solution(x bool) bool { - return x +func Solution(cost1 int, cost2 int, costBoth int, need1 int, need2 int) int64 { + // type1:1, type2:1, type3:各自+1 + // cost1 cost2 costBoth + i64cost1 := int64(cost1) + i64cost2 := int64(cost2) + i64both := int64(costBoth) + i64need1 := int64(need1) + i64need2 := int64(need2) + + // 1, 各自单买 + case1 := i64cost1*i64need1 + i64cost2*i64need2 + + // costBoth * min(need1, need2) + extra + extra2 := max(i64need2-i64need1, 0) + case2 := i64need1*i64both + extra2*i64cost2 + + extra1 := max(i64need1-i64need2, 0) + case3 := i64need2*i64both + extra1*i64cost1 + + // costBoth * max(need1, need2) + return min(case1, case2, case3, i64both*max(i64need1, i64need2)) } diff --git a/leetcode/3701-3800/3789.Minimum-Cost-to-Acquire-Required-Items/Solution_test.go b/leetcode/3701-3800/3789.Minimum-Cost-to-Acquire-Required-Items/Solution_test.go index 499883f0b..f5360fb45 100644 --- a/leetcode/3701-3800/3789.Minimum-Cost-to-Acquire-Required-Items/Solution_test.go +++ b/leetcode/3701-3800/3789.Minimum-Cost-to-Acquire-Required-Items/Solution_test.go @@ -9,22 +9,23 @@ import ( func TestSolution(t *testing.T) { // 测试用例 cases := []struct { - name string - inputs bool - expect bool + name string + c1, c2, cb, n1, n2 int + expect int64 }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", 3, 2, 1, 3, 2, 3}, + {"TestCase2", 5, 4, 15, 2, 3, 22}, + {"TestCase3", 5, 4, 15, 0, 0, 0}, } // 开始测试 for i, c := range cases { t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) { - got := Solution(c.inputs) + got := Solution(c.c1, c.c2, c.cb, c.n1, c.n2) 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 %v %v %v", + c.expect, got, c.c1, c.c2, c.cb, c.n1, c.n2) + } }) } diff --git a/leetcode/3801-3900/3818.Minimum-Prefix-Removal-to-Make-Array-Strictly-Increasing/README.md b/leetcode/3801-3900/3818.Minimum-Prefix-Removal-to-Make-Array-Strictly-Increasing/README.md index 1eb780045..fffc25f03 100644 --- a/leetcode/3801-3900/3818.Minimum-Prefix-Removal-to-Make-Array-Strictly-Increasing/README.md +++ b/leetcode/3801-3900/3818.Minimum-Prefix-Removal-to-Make-Array-Strictly-Increasing/README.md @@ -1,28 +1,47 @@ # [3818.Minimum Prefix Removal to Make Array Strictly Increasing][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`. + +You need to remove **exactly** one prefix (possibly empty) from nums. + +Return an integer denoting the **minimum** length of the removed prefix such that the remaining array is strictly increasing. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" +Input: nums = [1,-1,2,3,3,4,5] + +Output: 4 + +Explanation: + +Removing the prefix = [1, -1, 2, 3] leaves the remaining array [3, 4, 5] which is strictly increasing. ``` -## 题意 -> ... +**Example 2:** + +``` +Input: nums = [4,3,-2,-5] -## 题解 +Output: 3 + +Explanation: + +Removing the prefix = [4, 3, -2] leaves the remaining array [-5] which is strictly increasing. +``` + +**Example 3:** -### 思路1 -> ... -Minimum Prefix Removal to Make Array Strictly Increasing -```go ``` +Input: nums = [1,2,3,4] +Output: 0 + +Explanation: + +The array nums = [1, 2, 3, 4] is already strictly increasing so removing an empty prefix is sufficient. +``` ## 结语 diff --git a/leetcode/3801-3900/3818.Minimum-Prefix-Removal-to-Make-Array-Strictly-Increasing/Solution.go b/leetcode/3801-3900/3818.Minimum-Prefix-Removal-to-Make-Array-Strictly-Increasing/Solution.go index d115ccf5e..94b7744db 100644 --- a/leetcode/3801-3900/3818.Minimum-Prefix-Removal-to-Make-Array-Strictly-Increasing/Solution.go +++ b/leetcode/3801-3900/3818.Minimum-Prefix-Removal-to-Make-Array-Strictly-Increasing/Solution.go @@ -1,5 +1,12 @@ package Solution -func Solution(x bool) bool { - return x +func Solution(nums []int) int { + i := len(nums) - 1 + // 5 3 4 + for ; i > 0; i-- { + if nums[i] <= nums[i-1] { + break + } + } + return i } diff --git a/leetcode/3801-3900/3818.Minimum-Prefix-Removal-to-Make-Array-Strictly-Increasing/Solution_test.go b/leetcode/3801-3900/3818.Minimum-Prefix-Removal-to-Make-Array-Strictly-Increasing/Solution_test.go index 499883f0b..ff372c4b7 100644 --- a/leetcode/3801-3900/3818.Minimum-Prefix-Removal-to-Make-Array-Strictly-Increasing/Solution_test.go +++ b/leetcode/3801-3900/3818.Minimum-Prefix-Removal-to-Make-Array-Strictly-Increasing/Solution_test.go @@ -10,12 +10,12 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs []int + expect int }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", []int{1, -1, 2, 3, 3, 4, 5}, 4}, + {"TestCase2", []int{4, 3, -2, -5}, 3}, + {"TestCase3", []int{1, 2, 3, 4}, 0}, } // 开始测试 diff --git a/leetcode/3901-4000/3934.Smallest-Unique-Subarray/README.md b/leetcode/3901-4000/3934.Smallest-Unique-Subarray/README.md index 90aaa0322..1a6d0ecc1 100644 --- a/leetcode/3901-4000/3934.Smallest-Unique-Subarray/README.md +++ b/leetcode/3901-4000/3934.Smallest-Unique-Subarray/README.md @@ -1,28 +1,67 @@ # [3934.Smallest Unique Subarray][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`. + +Find the **minimum** length of a subarray that is **not identical** to any other **subarray** in `nums`. + +Return an integer denoting the **minimum possible length** of such a **subarray**. + +Two **subarrays** are considered identical if they have the same length and the same elements in corresponding positions. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" +Input: nums = [3,3,3] + +Output: 3 + +Explanation: + +Subarrays of length 1: [3] → appears 3 times +Subarrays of length 2: [3, 3] → appears 2 times +Subarrays of length 3: [3, 3, 3] → appears once +The subarray [3, 3, 3] is unique, so the smallest unique subarray length is 3. +``` + +**Example 2:** + ``` +Input: nums = [2,1,2,3,3] -## 题意 -> ... +Output: 1 -## 题解 +Explanation: -### 思路1 -> ... -Smallest Unique Subarray -```go +Subarrays of length 1: + +[2] → appears 2 times +[1] → appears once +[3] → appears 2 times +The subarray [1] is unique, so the smallest unique subarray length is 1. ``` +**Example 3:** + +``` +Input: nums = [1,1,2,2,1] + +Output: 2 + +Explanation: + +Subarrays of length 1: + +[1] → appears 3 times +[2] → appears 2 times +Subarrays of length 2: + +[1, 1] → appears once +[1, 2] → appears once +[2, 2] → appears once +[2, 1] → appears once +There is at least one subarray of length 2 that is unique, so the smallest unique subarray length is 2. +``` ## 结语 diff --git a/leetcode/3901-4000/3934.Smallest-Unique-Subarray/Solution.go b/leetcode/3901-4000/3934.Smallest-Unique-Subarray/Solution.go index d115ccf5e..6b7364cf5 100644 --- a/leetcode/3901-4000/3934.Smallest-Unique-Subarray/Solution.go +++ b/leetcode/3901-4000/3934.Smallest-Unique-Subarray/Solution.go @@ -1,5 +1,122 @@ package Solution -func Solution(x bool) bool { - return x +func Solution(nums []int) int { + n := len(nums) + + sa := make([]int, n) + rank := make([]int, n) + nextRank := make([]int, n) + + maxRank := 0 + for i, num := range nums { + sa[i] = i + rank[i] = num + maxRank = max(maxRank, num) + } + + // Construct the sorted suffix array by doubling + temp := make([]int, n) + cnt := make([]int, max(n+1, maxRank+2)) + + countingSort := func(getKey func(int) int) { + clear(cnt[:maxRank+2]) + + for _, i := range sa { + cnt[getKey(i)]++ + } + + for i := 1; i <= maxRank+1; i++ { + cnt[i] += cnt[i-1] + } + + for p := n - 1; p >= 0; p-- { + i := sa[p] + key := getKey(i) + cnt[key]-- + temp[cnt[key]] = i + } + + sa, temp = temp, sa + } + + for k := 1; k < n; k <<= 1 { + // Sort by the second key, then stably sort by the first key + countingSort(func(i int) int { + if i+k < n { + return rank[i+k] + 1 + } + return 0 + }) + countingSort(func(i int) int { + return rank[i] + 1 + }) + + nextRank[sa[0]] = 0 + + // Assign ranks to the newly sorted suffixes + for i := 1; i < n; i++ { + x, y := sa[i-1], sa[i] + rx, ry := -1, -1 + if x+k < n { + rx = rank[x+k] + } + if y+k < n { + ry = rank[y+k] + } + + nextRank[y] = nextRank[x] + if rank[x] != rank[y] || rx != ry { + nextRank[y]++ + } + } + + rank, nextRank = nextRank, rank + maxRank = rank[sa[n-1]] + + // All n suffixes have distinct ranks, so sorting is complete + if maxRank == n-1 { + break + } + } + + // Construct LCP using Kasai's algorithm + pos := make([]int, n) + lcp := make([]int, n) + for i, index := range sa { + pos[index] = i + } + + h := 0 + for i := 0; i < n; i++ { + if pos[i] == 0 { + h = 0 + continue + } + + j := sa[pos[i]-1] + for i+h < n && j+h < n && nums[i+h] == nums[j+h] { + h++ + } + + lcp[pos[i]] = h + + if h > 0 { + h-- + } + } + + answer := n + for i := 0; i < n; i++ { + next := 0 + if i+1 < n { + next = lcp[i+1] + } + + need := max(lcp[i], next) + 1 + if sa[i]+need <= n { + answer = min(answer, need) + } + } + + return answer } diff --git a/leetcode/3901-4000/3934.Smallest-Unique-Subarray/Solution_test.go b/leetcode/3901-4000/3934.Smallest-Unique-Subarray/Solution_test.go index 499883f0b..a221401b0 100644 --- a/leetcode/3901-4000/3934.Smallest-Unique-Subarray/Solution_test.go +++ b/leetcode/3901-4000/3934.Smallest-Unique-Subarray/Solution_test.go @@ -10,12 +10,12 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs []int + expect int }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", []int{3, 3, 3}, 3}, + {"TestCase2", []int{2, 1, 2, 3, 3}, 1}, + {"TestCase3", []int{1, 1, 2, 2, 1}, 2}, } // 开始测试 diff --git a/leetcode/3901-4000/3945.Digit-Frequency-Score/README.md b/leetcode/3901-4000/3945.Digit-Frequency-Score/README.md index d4521546b..350cff798 100644 --- a/leetcode/3901-4000/3945.Digit-Frequency-Score/README.md +++ b/leetcode/3901-4000/3945.Digit-Frequency-Score/README.md @@ -1,28 +1,39 @@ # [3945.Digit Frequency Score][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 `n`. + +The **score** of n is defined as the **sum** of `d * freq(d)` over all **distinct** digits `d`, where `freq(d)` denotes the number of times the digit `d` appears in `n`. + +Return an integer denoting the score of `n`. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" -``` +Input: n = 122 + +Output: 5 -## 题意 -> ... +Explanation: -## 题解 +The digit 1 appears 1 time, contributing 1 * 1 = 1. +The digit 2 appears 2 times, contributing 2 * 2 = 4. +Thus, the score of n is 1 + 4 = 5. +``` + +**Example 2:** -### 思路1 -> ... -Digit Frequency Score -```go ``` +Input: n = 101 + +Output: 2 +Explanation: + +The digit 0 appears 1 time, contributing 0 * 1 = 0. +The digit 1 appears 2 times, contributing 1 * 2 = 2. +Thus, the score of n is 2. +``` ## 结语 diff --git a/leetcode/3901-4000/3945.Digit-Frequency-Score/Solution.go b/leetcode/3901-4000/3945.Digit-Frequency-Score/Solution.go index d115ccf5e..3884f167b 100644 --- a/leetcode/3901-4000/3945.Digit-Frequency-Score/Solution.go +++ b/leetcode/3901-4000/3945.Digit-Frequency-Score/Solution.go @@ -1,5 +1,14 @@ package Solution -func Solution(x bool) bool { - return x +func Solution(n int) int { + digit := [10]int{} + var ret int + for n > 0 { + digit[n%10]++ + n /= 10 + } + for i := range 10 { + ret += i * digit[i] + } + return ret } diff --git a/leetcode/3901-4000/3945.Digit-Frequency-Score/Solution_test.go b/leetcode/3901-4000/3945.Digit-Frequency-Score/Solution_test.go index 499883f0b..2f04b9c9a 100644 --- a/leetcode/3901-4000/3945.Digit-Frequency-Score/Solution_test.go +++ b/leetcode/3901-4000/3945.Digit-Frequency-Score/Solution_test.go @@ -10,12 +10,11 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs int + expect int }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", 122, 5}, + {"TestCase2", 101, 2}, } // 开始测试 diff --git a/leetcode/3901-4000/3946.Maximum-Number-of-Items-From-Sale-I/README.md b/leetcode/3901-4000/3946.Maximum-Number-of-Items-From-Sale-I/README.md index 78f345d43..663931896 100644 --- a/leetcode/3901-4000/3946.Maximum-Number-of-Items-From-Sale-I/README.md +++ b/leetcode/3901-4000/3946.Maximum-Number-of-Items-From-Sale-I/README.md @@ -1,28 +1,47 @@ # [3946.Maximum Number of Items From Sale I][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 a 2D integer array `items`, where `items[i] = [factori, pricei]` represents the `ith` item. You are also given an integer `budget`. + +There are unlimited copies of each item available for purchase.You may buy any number of copies of any items such that the total cost of the purchased copies is at most `budget`. + +After buying items, you may receive free copies according to the following rules: + +- For each item `i` that you bought **at least one copy** of, you receive **one free copy** of every item `j` such that `j != i` and `factori` divides `factorj`. +- Buying multiple copies of the same item `i` does **not** give additional free copies through item `i`. +- The same item `j` can be received multiple times for free if it is received from purchases of different item types. + +Return the **maximum total number of item copies** you can obtain, including both purchased copies and free copies, while spending at most `budget` on purchased items. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" -``` +Input: items = [[6,2],[2,6],[3,4]], budget = 9 -## 题意 -> ... +Output: 4 -## 题解 +Explanation: -### 思路1 -> ... -Maximum Number of Items From Sale I -```go +You can buy 2 copies of item 0 and 1 copy of item 2 for a total cost of 2 * 2 + 4 = 8, which is not greater than budget = 9. +Buying item 2 gives 1 free copy of item 0, because factor2 = 3 divides factor0 = 6. +You leave with 3 purchased copies and 1 free copy, for a total of 4 item copies. ``` +**Example 2:** + +``` +Input: items = [[2,4],[3,2],[4,1],[6,4],[12,4]], budget = 8 + +Output: 10 + +Explanation: + +You can buy 1 copy of item 0, 1 copy of item 1, and 2 copies of item 2 for a total cost of 4 + 2 + 2 * 1 = 8. +Buying item 0 gives 1 free copy of items 2, 3, and 4. +Buying item 1 gives 1 free copy of items 3 and 4. +Buying item 2 gives 1 free copy of item 4. +Thus, you receive 6 free copies. You leave with 4 purchased copies and 6 free copies, for a total of 10 item copies. +``` ## 结语 diff --git a/leetcode/3901-4000/3946.Maximum-Number-of-Items-From-Sale-I/Solution.go b/leetcode/3901-4000/3946.Maximum-Number-of-Items-From-Sale-I/Solution.go index d115ccf5e..86fdcffe0 100644 --- a/leetcode/3901-4000/3946.Maximum-Number-of-Items-From-Sale-I/Solution.go +++ b/leetcode/3901-4000/3946.Maximum-Number-of-Items-From-Sale-I/Solution.go @@ -1,5 +1,24 @@ package Solution -func Solution(x bool) bool { - return x +func Solution(items [][]int, budget int) int { + f := make([]int, budget+1) + mn := items[0][1] + for _, item := range items { + factor, price := item[0], item[1] + mn = min(mn, price) + cnt := 0 + for _, other := range items { + if other[0]%factor == 0 { + cnt++ + } + } + for j := budget; j >= price; j-- { + f[j] = max(f[j], f[j-price]+cnt) + } + } + ans := 0 + for j := 0; j <= budget; j++ { + ans = max(ans, f[j]+(budget-j)/mn) + } + return ans } diff --git a/leetcode/3901-4000/3946.Maximum-Number-of-Items-From-Sale-I/Solution_test.go b/leetcode/3901-4000/3946.Maximum-Number-of-Items-From-Sale-I/Solution_test.go index 499883f0b..818389ef7 100644 --- a/leetcode/3901-4000/3946.Maximum-Number-of-Items-From-Sale-I/Solution_test.go +++ b/leetcode/3901-4000/3946.Maximum-Number-of-Items-From-Sale-I/Solution_test.go @@ -10,21 +10,21 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs [][]int + budget int + expect int }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", [][]int{{6, 2}, {2, 6}, {3, 4}}, 9, 4}, + {"TestCase2", [][]int{{2, 4}, {3, 2}, {4, 1}, {6, 4}, {12, 4}}, 8, 10}, } // 开始测试 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.budget) 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.budget) } }) } diff --git a/leetcode/3901-4000/3947.Maximum-Number-of-Items-From-Sale-II/README.md b/leetcode/3901-4000/3947.Maximum-Number-of-Items-From-Sale-II/README.md index 01ab69826..27c339c52 100644 --- a/leetcode/3901-4000/3947.Maximum-Number-of-Items-From-Sale-II/README.md +++ b/leetcode/3901-4000/3947.Maximum-Number-of-Items-From-Sale-II/README.md @@ -1,28 +1,50 @@ # [3947.Maximum Number of Items From Sale II][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 a 2D integer array `items`, where `items[i] = [factori, pricei]` represents the `ith` item. You are also given an integer `budget`. + +There are unlimited copies of each item available for purchase. You may buy any number of copies of any items such that the total cost of the purchased copies is at most `budget`. + +After buying items, you may receive free copies according to the following rules: + +- Each purchased copy of item `i` can give you **at most one** free copy of another item `j`. +- The free item must satisfy `i != j` and `factori` divides `factorj`. +- For each ordered pair `(i, j)`, you can receive a free copy of item `j` from purchases of item `i` **at most once**, regardless of how many copies of item `i` you buy. +- The same item `j` can be received multiple times for free if it is received from purchases of different item types. + +Return the **maximum total number of item copies** you can obtain, including both purchased copies and free copies, while spending at most `budget` on purchased items. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" -``` +Input: items = [[1,6],[2,4],[3,5]], budget = 19 -## 题意 -> ... +Output: 5 -## 题解 +Explanation: -### 思路1 -> ... -Maximum Number of Items From Sale II -```go +You can buy 2 copies of item 0 and 1 copy of item 1 for a total cost of 2 * 6 + 4 = 16, which is not greater than budget = 19. +One purchased copy of item 0 gives 1 free copy of item 1, because factor0 = 1 divides factor1 = 2. +The other purchased copy of item 0 gives 1 free copy of item 2, because factor0 = 1 divides factor2 = 3. +You leave with 3 purchased copies and 2 free copies, for a total of 5 item copies. ``` +**Example 2:** + +``` +Input: items = [[2,8],[1,10],[6,6],[4,12],[5,20],[5,17]], budget = 35 + +Output: 7 + +Explanation: + +You can buy 2 copies of item 0, 1 copy of item 1, and 1 copy of item 2 for a total cost of 2 * 8 + 10 + 6 = 32, which is not greater than budget = 35. +One purchased copy of item 0 gives 1 free copy of item 2, because factor0 = 2 divides factor2 = 6. +The other purchased copy of item 0 gives 1 free copy of item 3, because factor0 = 2 divides factor3 = 4. +The purchased copy of item 1 gives 1 free copy of item 2, because factor1 = 1 divides factor2 = 6. +Buying item 2 gives no free copy, because factor2 = 6 does not divide the factor of any other item. +You leave with 4 purchased copies and 3 free copies, for a total of 7 item copies. +``` ## 结语 diff --git a/leetcode/3901-4000/3947.Maximum-Number-of-Items-From-Sale-II/Solution.go b/leetcode/3901-4000/3947.Maximum-Number-of-Items-From-Sale-II/Solution.go index d115ccf5e..c88b89344 100644 --- a/leetcode/3901-4000/3947.Maximum-Number-of-Items-From-Sale-II/Solution.go +++ b/leetcode/3901-4000/3947.Maximum-Number-of-Items-From-Sale-II/Solution.go @@ -1,5 +1,39 @@ package Solution -func Solution(x bool) bool { - return x +import "slices" + +func Solution(items [][]int, budget int) int { + slices.SortFunc(items, func(a, b []int) int { + return a[1] - b[1] + }) + mx := 0 + for _, item := range items { + mx = max(mx, item[0]) + } + freq := make([]int, mx+1) + for _, item := range items { + freq[item[0]]++ + } + for i := 1; i <= mx; i++ { + if freq[i] > 0 { + for j := i * 2; j <= mx; j += i { + freq[i] += freq[j] + } + } + } + + mn := items[0][1] + ans := 0 + for _, item := range items { + factor, price := item[0], item[1] + if price > mn*2 { + break + } + cnt := freq[factor] - 1 + take := min(cnt, budget/price) + ans += take * 2 + budget -= take * price + } + ans += budget / mn + return ans } diff --git a/leetcode/3901-4000/3947.Maximum-Number-of-Items-From-Sale-II/Solution_test.go b/leetcode/3901-4000/3947.Maximum-Number-of-Items-From-Sale-II/Solution_test.go index 499883f0b..d2758ad39 100644 --- a/leetcode/3901-4000/3947.Maximum-Number-of-Items-From-Sale-II/Solution_test.go +++ b/leetcode/3901-4000/3947.Maximum-Number-of-Items-From-Sale-II/Solution_test.go @@ -10,21 +10,21 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs [][]int + budget int + expect int }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", [][]int{{1, 6}, {2, 4}, {3, 5}}, 19, 5}, + {"TestCase2", [][]int{{2, 8}, {1, 10}, {6, 6}, {4, 12}, {5, 20}, {5, 17}}, 35, 7}, } // 开始测试 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.budget) 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.budget) } }) } diff --git a/leetcode/501-600/0598.Range-Addition-II/README.md b/leetcode/501-600/0598.Range-Addition-II/README.md index 6f56bb0e3..d721ddead 100644 --- a/leetcode/501-600/0598.Range-Addition-II/README.md +++ b/leetcode/501-600/0598.Range-Addition-II/README.md @@ -1,28 +1,33 @@ # [598.Range Addition II][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 `m x n` matrix `M` initialized with all `0`'s and an array of operations `ops`, where `ops[i] = [ai, bi]` means `M[x][y]` should be incremented by one for all `0 <= x < ai and 0 <= y < bi`. + +Count and return the number of maximum integers in the matrix after performing all the operations. -**Example 1:** +**Example 1:** + +![1](./ex1.jpg) ``` -Input: a = "11", b = "1" -Output: "100" +Input: m = 3, n = 3, ops = [[2,2],[3,3]] +Output: 4 +Explanation: The maximum integer in M is 2, and there are four of it in M. So return 4. ``` -## 题意 -> ... - -## 题解 +**Example 2:** -### 思路1 -> ... -Range Addition II -```go ``` +Input: m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]] +Output: 4 +``` + +**Example 3:** +``` +Input: m = 3, n = 3, ops = [] +Output: 9 +``` ## 结语 diff --git a/leetcode/501-600/0598.Range-Addition-II/Solution.go b/leetcode/501-600/0598.Range-Addition-II/Solution.go index d115ccf5e..fbc0f3ea4 100644 --- a/leetcode/501-600/0598.Range-Addition-II/Solution.go +++ b/leetcode/501-600/0598.Range-Addition-II/Solution.go @@ -1,5 +1,10 @@ package Solution -func Solution(x bool) bool { - return x +func Solution(m int, n int, ops [][]int) int { + minX, minY := m, n + for _, op := range ops { + minX = min(minX, op[0]) + minY = min(minY, op[1]) + } + return minX * minY } diff --git a/leetcode/501-600/0598.Range-Addition-II/Solution_test.go b/leetcode/501-600/0598.Range-Addition-II/Solution_test.go index 499883f0b..7ee2ac150 100644 --- a/leetcode/501-600/0598.Range-Addition-II/Solution_test.go +++ b/leetcode/501-600/0598.Range-Addition-II/Solution_test.go @@ -10,21 +10,26 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + m, n int + ops [][]int + expect int }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", 3, 3, [][]int{{2, 2}, {3, 3}}, 4}, + {"TestCase2", 3, 3, [][]int{ + {2, 2}, {3, 3}, {3, 3}, {3, 3}, + {2, 2}, {3, 3}, {3, 3}, {3, 3}, + {2, 2}, {3, 3}, {3, 3}, {3, 3}, + }, 4}, + {"TestCase3", 3, 3, [][]int{}, 9}, } // 开始测试 for i, c := range cases { t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) { - got := Solution(c.inputs) + got := Solution(c.m, c.n, c.ops) 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 %v", + c.expect, got, c.m, c.n, c.ops) } }) } diff --git a/leetcode/501-600/0598.Range-Addition-II/ex1.jpg b/leetcode/501-600/0598.Range-Addition-II/ex1.jpg new file mode 100644 index 000000000..80b701213 Binary files /dev/null and b/leetcode/501-600/0598.Range-Addition-II/ex1.jpg differ diff --git a/leetcode/901-1000/0908.Smallest-Range-I/README.md b/leetcode/901-1000/0908.Smallest-Range-I/README.md index 2b574e118..8ef2b7ef7 100644 --- a/leetcode/901-1000/0908.Smallest-Range-I/README.md +++ b/leetcode/901-1000/0908.Smallest-Range-I/README.md @@ -1,28 +1,37 @@ # [908.Smallest Range I][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`. + +In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this operation **at most once** for each index i. + +The **scope** of `nums` is the difference between the maximum and minimum elements in `nums`. + +Return the minimum **score** of nums after applying the mentioned operation at most once for each index in it. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" +Input: nums = [1], k = 0 +Output: 0 +Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0. ``` -## 题意 -> ... - -## 题解 +**Example 2:** -### 思路1 -> ... -Smallest Range I -```go ``` +Input: nums = [0,10], k = 2 +Output: 6 +Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6. +``` + +**Example 3:** +``` +Input: nums = [1,3,6], k = 3 +Output: 0 +Explanation: Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0. +``` ## 结语 diff --git a/leetcode/901-1000/0908.Smallest-Range-I/Solution.go b/leetcode/901-1000/0908.Smallest-Range-I/Solution.go index d115ccf5e..b2f95d733 100644 --- a/leetcode/901-1000/0908.Smallest-Range-I/Solution.go +++ b/leetcode/901-1000/0908.Smallest-Range-I/Solution.go @@ -1,5 +1,10 @@ package Solution -func Solution(x bool) bool { - return x +func Solution(nums []int, k int) int { + _max, _min := nums[0], nums[0] + for i := 1; i < len(nums); i++ { + _min = min(_min, nums[i]) + _max = max(_max, nums[i]) + } + return max(0, _max-_min-2*k) } diff --git a/leetcode/901-1000/0908.Smallest-Range-I/Solution_test.go b/leetcode/901-1000/0908.Smallest-Range-I/Solution_test.go index 499883f0b..b285c1c56 100644 --- a/leetcode/901-1000/0908.Smallest-Range-I/Solution_test.go +++ b/leetcode/901-1000/0908.Smallest-Range-I/Solution_test.go @@ -10,21 +10,22 @@ 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}, 0, 0}, + {"TestCase2", []int{0, 10}, 2, 6}, + {"TestCase3", []int{1, 3, 6}, 3, 0}, } // 开始测试 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) } }) }