diff --git a/articles/arranging-coins.md b/articles/arranging-coins.md index cb8920a4a..563ca3c80 100644 --- a/articles/arranging-coins.md +++ b/articles/arranging-coins.md @@ -56,6 +56,19 @@ class Solution { } ``` +```csharp +public class Solution { + public int ArrangeCoins(int n) { + int row = 0; + while (n - row > 0) { + row++; + n -= row; + } + return row; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -155,6 +168,29 @@ class Solution { } ``` +```csharp +public class Solution { + public int ArrangeCoins(int n) { + int l = 1, r = n; + int res = 0; + + while (l <= r) { + int mid = l + (r - l) / 2; + long coins = (long)mid * (mid + 1) / 2; + + if (coins > n) { + r = mid - 1; + } else { + res = Math.Max(res, mid); + l = mid + 1; + } + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -259,6 +295,30 @@ class Solution { } ``` +```csharp +public class Solution { + public int ArrangeCoins(int n) { + if (n <= 3) { + return n == 1 ? 1 : n - 1; + } + + int l = 1, r = (n / 2) + 1; + while (l < r) { + int mid = (l + r) / 2; + long coins = (long)mid * (mid + 1) / 2; + + if (coins <= n) { + l = mid + 1; + } else { + r = mid; + } + } + + return l - 1; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -345,6 +405,26 @@ class Solution { } ``` +```csharp +public class Solution { + public int ArrangeCoins(int n) { + int mask = 1 << 15; + int rows = 0; + + while (mask > 0) { + rows |= mask; + long coins = (long)rows * (rows + 1) / 2; + if (coins > n) { + rows ^= mask; + } + mask >>= 1; + } + + return rows; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -393,6 +473,14 @@ class Solution { } ``` +```csharp +public class Solution { + public int ArrangeCoins(int n) { + return (int)(Math.Sqrt(2L * n + 0.25) - 0.5); + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/buy-two-chocolates.md b/articles/buy-two-chocolates.md index 0b6edc79d..6ff3c2333 100644 --- a/articles/buy-two-chocolates.md +++ b/articles/buy-two-chocolates.md @@ -48,6 +48,11 @@ public: ```javascript class Solution { + /** + * @param {number[]} prices + * @param {number} money + * @return {number} + */ buyChoco(prices, money) { let res = -1; for (let i = 0; i < prices.length; i++) { @@ -62,6 +67,22 @@ class Solution { } ``` +```csharp +public class Solution { + public int BuyChoco(int[] prices, int money) { + int res = -1; + for (int i = 0; i < prices.Length; i++) { + for (int j = i + 1; j < prices.Length; j++) { + if (prices[i] + prices[j] <= money) { + res = Math.Max(res, money - prices[i] - prices[j]); + } + } + } + return res == -1 ? money : res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -106,6 +127,11 @@ public: ```javascript class Solution { + /** + * @param {number[]} prices + * @param {number} money + * @return {number} + */ buyChoco(prices, money) { prices.sort((a, b) => a - b); let buy = prices[0] + prices[1]; @@ -114,6 +140,16 @@ class Solution { } ``` +```csharp +public class Solution { + public int BuyChoco(int[] prices, int money) { + Array.Sort(prices); + int buy = prices[0] + prices[1]; + return buy > money ? money : money - buy; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -185,6 +221,11 @@ public: ```javascript class Solution { + /** + * @param {number[]} prices + * @param {number} money + * @return {number} + */ buyChoco(prices, money) { let min1 = Infinity, min2 = Infinity; @@ -203,6 +244,26 @@ class Solution { } ``` +```csharp +public class Solution { + public int BuyChoco(int[] prices, int money) { + int min1 = int.MaxValue, min2 = int.MaxValue; + + foreach (int p in prices) { + if (p < min1) { + min2 = min1; + min1 = p; + } else if (p < min2) { + min2 = p; + } + } + + int leftover = money - min1 - min2; + return leftover >= 0 ? leftover : money; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/count-odd-numbers-in-an-interval-range.md b/articles/count-odd-numbers-in-an-interval-range.md index 1cbaf37b8..cae6c6b8d 100644 --- a/articles/count-odd-numbers-in-an-interval-range.md +++ b/articles/count-odd-numbers-in-an-interval-range.md @@ -60,6 +60,20 @@ class Solution { } ``` +```csharp +public class Solution { + public int CountOdds(int low, int high) { + int odd = 0; + for (int num = low; num <= high; num++) { + if ((num & 1) == 1) { + odd++; + } + } + return odd; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -130,6 +144,19 @@ class Solution { } ``` +```csharp +public class Solution { + public int CountOdds(int low, int high) { + int length = high - low + 1; + int count = length / 2; + if ((length % 2 == 1) && (low % 2 == 1)) { + count++; + } + return count; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -179,6 +206,14 @@ class Solution { } ``` +```csharp +public class Solution { + public int CountOdds(int low, int high) { + return ((high + 1) >> 1) - (low >> 1); + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/crawler-log-folder.md b/articles/crawler-log-folder.md new file mode 100644 index 000000000..383bab91e --- /dev/null +++ b/articles/crawler-log-folder.md @@ -0,0 +1,208 @@ +## 1. Stack + +::tabs-start + +```python +class Solution: + def minOperations(self, logs: List[str]) -> int: + stack = [] + for log in logs: + if log == "../": + if stack: + stack.pop() + elif log != "./": + stack.append(log) + return len(stack) +``` + +```java +public class Solution { + public int minOperations(String[] logs) { + Stack stack = new Stack<>(); + for (String log : logs) { + if (log.equals("../")) { + if (!stack.isEmpty()) { + stack.pop(); + } + } else if (!log.equals("./")) { + stack.push(log); + } + } + return stack.size(); + } +} +``` + +```cpp +class Solution { +public: + int minOperations(vector& logs) { + stack st; + for (auto& log : logs) { + if (log == "../") { + if (!st.empty()) { + st.pop(); + } + } else if (log != "./") { + st.push(log); + } + } + return st.size(); + } +}; +``` + +```javascript +class Solution { + /** + * @param {string[]} logs + * @return {number} + */ + minOperations(logs) { + let stack = []; + for (let log of logs) { + if (log === "../") { + if (stack.length > 0) { + stack.pop(); + } + } else if (log !== "./") { + stack.push(log); + } + } + return stack.length; + } +} +``` + +```csharp +public class Solution { + public int MinOperations(string[] logs) { + Stack stack = new Stack(); + foreach (string log in logs) { + if (log == "../") { + if (stack.Count > 0) { + stack.Pop(); + } + } else if (log != "./") { + stack.Push(log); + } + } + return stack.Count; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(n)$ + +--- + +## 2. Iteration + +::tabs-start + +```python +class Solution: + def minOperations(self, logs: List[str]) -> int: + res = 0 + for log in logs: + if log == "./": + continue + if log == "../": + res = max(0, res - 1) + else: + res += 1 + return res +``` + +```java +public class Solution { + public int minOperations(String[] logs) { + int res = 0; + for (String log : logs) { + if (log.equals("./")) { + continue; + } + if (log.equals("../")) { + res = Math.max(0, res - 1); + } else { + res++; + } + } + return res; + } +} +``` + +```cpp +class Solution { +public: + int minOperations(vector& logs) { + int res = 0; + for (auto& log : logs) { + if (log == "./") { + continue; + } + if (log == "../") { + res = max(0, res - 1); + } else { + res++; + } + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {string[]} logs + * @return {number} + */ + minOperations(logs) { + let res = 0; + for (let log of logs) { + if (log === "./") { + continue; + } + if (log === "../") { + res = Math.max(0, res - 1); + } else { + res++; + } + } + return res; + } +} +``` + +```csharp +public class Solution { + public int MinOperations(string[] logs) { + int res = 0; + foreach (string log in logs) { + if (log == "./") { + continue; + } + if (log == "../") { + res = Math.Max(0, res - 1); + } else { + res++; + } + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ \ No newline at end of file diff --git a/articles/final-array-state-after-k-multiplication-operations-i.md b/articles/final-array-state-after-k-multiplication-operations-i.md new file mode 100644 index 000000000..1a5350dae --- /dev/null +++ b/articles/final-array-state-after-k-multiplication-operations-i.md @@ -0,0 +1,249 @@ +## 1. Simulation + +::tabs-start + +```python +class Solution: + def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]: + n = len(nums) + for _ in range(k): + minIdx = 0 + for i in range(1, n): + if nums[i] < nums[minIdx]: + minIdx = i + nums[minIdx] *= multiplier + return nums +``` + +```java +public class Solution { + public int[] getFinalState(int[] nums, int k, int multiplier) { + int n = nums.length; + for (int j = 0; j < k; j++) { + int minIdx = 0; + for (int i = 1; i < n; i++) { + if (nums[i] < nums[minIdx]) { + minIdx = i; + } + } + nums[minIdx] *= multiplier; + } + return nums; + } +} +``` + +```cpp +class Solution { +public: + vector getFinalState(vector& nums, int k, int multiplier) { + int n = nums.size(); + for (int _ = 0; _ < k; _++) { + int minIdx = 0; + for (int i = 1; i < n; i++) { + if (nums[i] < nums[minIdx]) { + minIdx = i; + } + } + nums[minIdx] *= multiplier; + } + return nums; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @param {number} k + * @param {number} multiplier + * @return {number[]} + */ + getFinalState(nums, k, multiplier) { + let n = nums.length; + for (let _ = 0; _ < k; _++) { + let minIdx = 0; + for (let i = 1; i < n; i++) { + if (nums[i] < nums[minIdx]) { + minIdx = i; + } + } + nums[minIdx] *= multiplier; + } + return nums; + } +} +``` + +```csharp +public class Solution { + public int[] GetFinalState(int[] nums, int k, int multiplier) { + int n = nums.Length; + for (int _ = 0; _ < k; _++) { + int minIdx = 0; + for (int i = 1; i < n; i++) { + if (nums[i] < nums[minIdx]) { + minIdx = i; + } + } + nums[minIdx] *= multiplier; + } + return nums; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n * k)$ +* Space complexity: $O(1)$ extra space. + +> Where $n$ is the size of the input array, and $k$ is the number of operations. + +--- + +## 2. Min-Heap + +::tabs-start + +```python +class Solution: + def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]: + res = nums[:] + + min_heap = [(num, i) for i, num in enumerate(nums)] + heapq.heapify(min_heap) + + for _ in range(k): + num, i = heapq.heappop(min_heap) + res[i] *= multiplier + heapq.heappush(min_heap, (res[i], i)) + + return res +``` + +```java +public class Solution { + public int[] getFinalState(int[] nums, int k, int multiplier) { + int n = nums.length; + int[] res = Arrays.copyOf(nums, n); + + PriorityQueue minHeap = new PriorityQueue<>((a, b) -> { + if (res[a] != res[b]) return Integer.compare(res[a], res[b]); + return Integer.compare(a, b); + }); + + for (int i = 0; i < n; i++) { + minHeap.add(i); + } + + for (int i = 0; i < k; i++) { + int idx = minHeap.poll(); + res[idx] *= multiplier; + minHeap.add(idx); + } + + return res; + } +} +``` + +```cpp +class Solution { +public: + vector getFinalState(vector& nums, int k, int multiplier) { + int n = nums.size(); + vector res = nums; + + auto cmp = [&](int a, int b) { + if (res[a] != res[b]) return res[a] > res[b]; + return a > b; + }; + priority_queue, decltype(cmp)> minHeap(cmp); + + for (int i = 0; i < n; i++) { + minHeap.push(i); + } + + for (int _ = 0; _ < k; _++) { + int i = minHeap.top(); + minHeap.pop(); + res[i] *= multiplier; + minHeap.push(i); + } + + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @param {number} k + * @param {number} multiplier + * @return {number[]} + */ + getFinalState(nums, k, multiplier) { + let res = nums.slice(); + let n = res.length; + let minHeap = new PriorityQueue((a, b) => { + if (res[a] !== res[b]) { + return res[a] - res[b]; + } + return a - b; + }); + + for (let i = 0; i < n; i++) { + minHeap.enqueue(i); + } + + for (let _ = 0; _ < k; _++) { + let i = minHeap.dequeue(); + res[i] *= multiplier; + minHeap.enqueue(i); + } + + return res; + } +} +``` + +```csharp +public class Solution { + public int[] GetFinalState(int[] nums, int k, int multiplier) { + int n = nums.Length; + int[] res = new int[n]; + Array.Copy(nums, res, n); + + var minHeap = new PriorityQueue(); + for (int i = 0; i < n; i++) { + minHeap.Enqueue(i, (res[i], i)); + } + + for (int _ = 0; _ < k; _++) { + int i = minHeap.Dequeue(); + res[i] *= multiplier; + minHeap.Enqueue(i, (res[i], i)); + } + + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: + - $O(n + k \log n)$ in Python. + - $O(n \log n + k \log n)$ in other languages. + +* Space complexity: $O(n)$ + +> Where $n$ is the size of the input array, and $k$ is the number of operations. \ No newline at end of file diff --git a/articles/grumpy-bookstore-owner.md b/articles/grumpy-bookstore-owner.md new file mode 100644 index 000000000..0f4b15d95 --- /dev/null +++ b/articles/grumpy-bookstore-owner.md @@ -0,0 +1,293 @@ +## 1. Brute Force + +::tabs-start + +```python +class Solution: + def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int: + res, n = 0, len(customers) + for i in range(n): + if not grumpy[i]: + res += customers[i] + + satisfied = res + for i in range(n - minutes + 1): + cur = 0 + for j in range(i, i + minutes): + if grumpy[j]: + cur += customers[j] + res = max(res, satisfied + cur) + + return res +``` + +```java +public class Solution { + public int maxSatisfied(int[] customers, int[] grumpy, int minutes) { + int res = 0, n = customers.length; + for (int i = 0; i < n; i++) { + if (grumpy[i] == 0) { + res += customers[i]; + } + } + + int satisfied = res; + for (int i = 0; i <= n - minutes; i++) { + int cur = 0; + for (int j = i; j < i + minutes; j++) { + if (grumpy[j] == 1) { + cur += customers[j]; + } + } + res = Math.max(res, satisfied + cur); + } + + return res; + } +} +``` + +```cpp +class Solution { +public: + int maxSatisfied(vector& customers, vector& grumpy, int minutes) { + int res = 0, n = customers.size(); + for (int i = 0; i < n; i++) { + if (grumpy[i] == 0) { + res += customers[i]; + } + } + + int satisfied = res; + for (int i = 0; i <= n - minutes; i++) { + int cur = 0; + for (int j = i; j < i + minutes; j++) { + if (grumpy[j] == 1) { + cur += customers[j]; + } + } + res = max(res, satisfied + cur); + } + + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} customers + * @param {number[]} grumpy + * @param {number} minutes + * @return {number} + */ + maxSatisfied(customers, grumpy, minutes) { + let res = 0, n = customers.length; + for (let i = 0; i < n; i++) { + if (grumpy[i] === 0) { + res += customers[i]; + } + } + + let satisfied = res; + for (let i = 0; i <= n - minutes; i++) { + let cur = 0; + for (let j = i; j < i + minutes; j++) { + if (grumpy[j] === 1) { + cur += customers[j]; + } + } + res = Math.max(res, satisfied + cur); + } + + return res; + } +} +``` + +```csharp +public class Solution { + public int MaxSatisfied(int[] customers, int[] grumpy, int minutes) { + int res = 0, n = customers.Length; + for (int i = 0; i < n; i++) { + if (grumpy[i] == 0) { + res += customers[i]; + } + } + + int satisfied = res; + for (int i = 0; i <= n - minutes; i++) { + int cur = 0; + for (int j = i; j < i + minutes; j++) { + if (grumpy[j] == 1) { + cur += customers[j]; + } + } + res = Math.Max(res, satisfied + cur); + } + + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n * m)$ +* Space complexity: $O(1)$ + +> Where $n$ is the size of the input array and $m$ is the number of minutes. + +--- + +## 2. Sliding Window + +::tabs-start + +```python +class Solution: + def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int: + l = 0 + window = max_window = 0 + satisfied = 0 + + for r in range(len(customers)): + if grumpy[r]: + window += customers[r] + else: + satisfied += customers[r] + + if r - l + 1 > minutes: + if grumpy[l]: + window -= customers[l] + l += 1 + + max_window = max(window, max_window) + + return satisfied + max_window +``` + +```java +public class Solution { + public int maxSatisfied(int[] customers, int[] grumpy, int minutes) { + int l = 0, window = 0, maxWindow = 0, satisfied = 0; + + for (int r = 0; r < customers.length; r++) { + if (grumpy[r] == 1) { + window += customers[r]; + } else { + satisfied += customers[r]; + } + + if (r - l + 1 > minutes) { + if (grumpy[l] == 1) { + window -= customers[l]; + } + l++; + } + + maxWindow = Math.max(window, maxWindow); + } + + return satisfied + maxWindow; + } +} +``` + +```cpp +class Solution { +public: + int maxSatisfied(vector& customers, vector& grumpy, int minutes) { + int l = 0, window = 0, maxWindow = 0, satisfied = 0; + + for (int r = 0; r < customers.size(); r++) { + if (grumpy[r] == 1) { + window += customers[r]; + } else { + satisfied += customers[r]; + } + + if (r - l + 1 > minutes) { + if (grumpy[l] == 1) { + window -= customers[l]; + } + l++; + } + + maxWindow = max(window, maxWindow); + } + + return satisfied + maxWindow; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} customers + * @param {number[]} grumpy + * @param {number} minutes + * @return {number} + */ + maxSatisfied(customers, grumpy, minutes) { + let l = 0, window = 0, maxWindow = 0, satisfied = 0; + + for (let r = 0; r < customers.length; r++) { + if (grumpy[r] === 1) { + window += customers[r]; + } else { + satisfied += customers[r]; + } + + if (r - l + 1 > minutes) { + if (grumpy[l] === 1) { + window -= customers[l]; + } + l++; + } + + maxWindow = Math.max(window, maxWindow); + } + + return satisfied + maxWindow; + } +} +``` + +```csharp +public class Solution { + public int MaxSatisfied(int[] customers, int[] grumpy, int minutes) { + int l = 0, window = 0, maxWindow = 0, satisfied = 0; + + for (int r = 0; r < customers.Length; r++) { + if (grumpy[r] == 1) { + window += customers[r]; + } else { + satisfied += customers[r]; + } + + if (r - l + 1 > minutes) { + if (grumpy[l] == 1) { + window -= customers[l]; + } + l++; + } + + maxWindow = Math.Max(window, maxWindow); + } + + return satisfied + maxWindow; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ \ No newline at end of file diff --git a/articles/interleaving-string.md b/articles/interleaving-string.md index 3d124cd01..bc8928fe9 100644 --- a/articles/interleaving-string.md +++ b/articles/interleaving-string.md @@ -776,12 +776,13 @@ class Solution: if n < m: s1, s2 = s2, s1 m, n = n, m - + dp = [False for _ in range(n + 1)] dp[n] = True for i in range(m, -1, -1): nextDp = [False for _ in range(n + 1)] - nextDp[n] = True + if i == m: + nextDp[n] = True for j in range(n, -1, -1): if i < m and s1[i] == s3[i + j] and dp[j]: nextDp[j] = True @@ -804,12 +805,12 @@ public class Solution { m = n; n = tempLength; } - + boolean[] dp = new boolean[n + 1]; dp[n] = true; for (int i = m; i >= 0; i--) { boolean[] nextDp = new boolean[n + 1]; - nextDp[n] = true; + if (i == m) nextDp[n] = true; for (int j = n; j >= 0; j--) { if (i < m && s1.charAt(i) == s3.charAt(i + j) && dp[j]) { nextDp[j] = true; @@ -835,12 +836,12 @@ public: swap(s1, s2); swap(m, n); } - + vector dp(n + 1); dp[n] = true; for (int i = m; i >= 0; --i) { vector nextDp(n + 1); - nextDp[n] = true; + if (i == m) nextDp[n] = true; for (int j = n; j >= 0; --j) { if (i < m && s1[i] == s3[i + j] && dp[j]) { nextDp[j] = true; @@ -876,7 +877,7 @@ class Solution { dp[n] = true; for (let i = m; i >= 0; i--) { let nextDp = Array(n + 1).fill(false); - nextDp[n] = true; + if (i === m) nextDp[n] = true; for (let j = n; j >= 0; j--) { if (i < m && s1[i] === s3[i + j] && dp[j]) { nextDp[j] = true; @@ -905,12 +906,12 @@ public class Solution { m = n; n = tempLength; } - + bool[] dp = new bool[n + 1]; dp[n] = true; for (int i = m; i >= 0; i--) { bool[] nextDp = new bool[n + 1]; - nextDp[n] = true; + if (i == m) nextDp[n] = true; for (int j = n; j >= 0; j--) { if (i < m && s1[i] == s3[i + j] && dp[j]) { nextDp[j] = true; @@ -941,7 +942,9 @@ func isInterleave(s1 string, s2 string, s3 string) bool { dp[n] = true for i := m; i >= 0; i-- { nextDp := make([]bool, n+1) - nextDp[n] = true + if i == m { + nextDp[n] = true + } for j := n; j >= 0; j-- { if i < m && s1[i] == s3[i+j] && dp[j] { nextDp[j] = true @@ -980,7 +983,7 @@ class Solution { dp[n] = true for (i in m downTo 0) { val nextDp = BooleanArray(n + 1) - nextDp[n] = true + if (i == m) nextDp[n] = true for (j in n downTo 0) { if (i < m && s1[i] == s3[i + j] && dp[j]) { nextDp[j] = true @@ -1012,7 +1015,9 @@ class Solution { for i in stride(from: m, through: 0, by: -1) { var nextDp = Array(repeating: false, count: n + 1) - nextDp[n] = true + if i == m { + nextDp[n] = true + } for j in stride(from: n, through: 0, by: -1) { if i < m && s1[i] == s3[i + j] && dp[j] { nextDp[j] = true @@ -1052,13 +1057,13 @@ class Solution: if n < m: s1, s2 = s2, s1 m, n = n, m - + dp = [False for _ in range(n + 1)] dp[n] = True for i in range(m, -1, -1): - nextDp = True - for j in range(n - 1, -1, -1): - res = False + nextDp = True if i == m else False + for j in range(n, -1, -1): + res = False if j < n else nextDp if i < m and s1[i] == s3[i + j] and dp[j]: res = True if j < n and s2[j] == s3[i + j] and nextDp: @@ -1085,9 +1090,9 @@ public class Solution { boolean[] dp = new boolean[n + 1]; dp[n] = true; for (int i = m; i >= 0; i--) { - boolean nextDp = true; - for (int j = n - 1; j >= 0; j--) { - boolean res = false; + boolean nextDp = (i == m ? true : false); + for (int j = n; j >= 0; j--) { + boolean res = (j < n ? false : nextDp); if (i < m && s1.charAt(i) == s3.charAt(i + j) && dp[j]) { res = true; } @@ -1117,9 +1122,9 @@ public: vector dp(n + 1, false); dp[n] = true; for (int i = m; i >= 0; i--) { - bool nextDp = true; - for (int j = n - 1; j >= 0; j--) { - bool res = false; + bool nextDp = (i == m ? true : false); + for (int j = n; j >= 0; j--) { + bool res = (j < n ? false : nextDp); if (i < m && s1[i] == s3[i + j] && dp[j]) { res = true; } @@ -1154,9 +1159,9 @@ class Solution { let dp = Array(n + 1).fill(false); dp[n] = true; for (let i = m; i >= 0; i--) { - let nextDp = true; - for (let j = n - 1; j >= 0; j--) { - let res = false; + let nextDp = (i === m ? true : false); + for (let j = n; j >= 0; j--) { + let res = (j < n ? false : nextDp); if (i < m && s1[i] === s3[i + j] && dp[j]) { res = true; } @@ -1189,9 +1194,9 @@ public class Solution { bool[] dp = new bool[n + 1]; dp[n] = true; for (int i = m; i >= 0; i--) { - bool nextDp = true; - for (int j = n - 1; j >= 0; j--) { - bool res = false; + bool nextDp = (i == m ? true : false); + for (int j = n; j >= 0; j--) { + bool res = (j < n ? false : nextDp); if (i < m && s1[i] == s3[i + j] && dp[j]) { res = true; } @@ -1221,9 +1226,12 @@ func isInterleave(s1, s2, s3 string) bool { dp := make([]bool, n+1) dp[n] = true for i := m; i >= 0; i-- { - nextDp := true - for j := n - 1; j >= 0; j-- { - res := false + nextDp := (i == m) + for j := n; j >= 0; j-- { + res := nextDp + if j < n { + res = false + } if i < m && s1[i] == s3[i+j] && dp[j] { res = true } @@ -1261,9 +1269,10 @@ class Solution { val dp = BooleanArray(n + 1) dp[n] = true for (i in m downTo 0) { - var nextDp = true - for (j in n - 1 downTo 0) { - var res = false + var nextDp = (i == m) + for (j in n downTo 0) { + var res = nextDp + if (j < n) res = false if (i < m && s1[i] == s3[i + j] && dp[j]) { res = true } @@ -1294,9 +1303,12 @@ class Solution { dp[n] = true for i in stride(from: m, through: 0, by: -1) { - var nextDp = true - for j in stride(from: n - 1, through: 0, by: -1) { - var res = false + var nextDp = (i == m) + for j in stride(from: n, through: 0, by: -1) { + var res = nextDp + if j < n { + res = false + } if i < m && s1[i] == s3[i + j] && dp[j] { res = true } diff --git a/articles/is-subsequence.md b/articles/is-subsequence.md index fde7628a6..6d85c6960 100644 --- a/articles/is-subsequence.md +++ b/articles/is-subsequence.md @@ -72,6 +72,24 @@ class Solution { } ``` +```csharp +public class Solution { + public bool IsSubsequence(string s, string t) { + return Rec(0, 0, s, t); + } + + private bool Rec(int i, int j, string s, string t) { + if (i == s.Length) return true; + if (j == t.Length) return false; + + if (s[i] == t[j]) { + return Rec(i + 1, j + 1, s, t); + } + return Rec(i, j + 1, s, t); + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -186,6 +204,33 @@ class Solution { } ``` +```csharp +public class Solution { + public bool IsSubsequence(string s, string t) { + int n = s.Length, m = t.Length; + int[,] memo = new int[n, m]; + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++) + memo[i, j] = -1; + + bool Rec(int i, int j) { + if (i == n) return true; + if (j == m) return false; + if (memo[i, j] != -1) return memo[i, j] == 1; + + if (s[i] == t[j]) { + memo[i, j] = Rec(i + 1, j + 1) ? 1 : 0; + } else { + memo[i, j] = Rec(i, j + 1) ? 1 : 0; + } + return memo[i, j] == 1; + } + + return Rec(0, 0); + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -301,6 +346,31 @@ class Solution { } ``` +```csharp +public class Solution { + public bool IsSubsequence(string s, string t) { + int n = s.Length, m = t.Length; + bool[,] dp = new bool[n + 1, m + 1]; + + for (int j = 0; j <= m; j++) { + dp[n, j] = true; + } + + for (int i = n - 1; i >= 0; i--) { + for (int j = m - 1; j >= 0; j--) { + if (s[i] == t[j]) { + dp[i, j] = dp[i + 1, j + 1]; + } else { + dp[i, j] = dp[i, j + 1]; + } + } + } + + return dp[0, 0]; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -378,6 +448,21 @@ class Solution { } ``` +```csharp +public class Solution { + public bool IsSubsequence(string s, string t) { + int i = 0, j = 0; + while (i < s.Length && j < t.Length) { + if (s[i] == t[j]) { + i++; + } + j++; + } + return i == s.Length; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -503,6 +588,40 @@ class Solution { } ``` +```csharp +public class Solution { + public bool IsSubsequence(string s, string t) { + int n = s.Length, m = t.Length; + if (m == 0) return n == 0; + + int[,] store = new int[m, 26]; + for (int i = 0; i < 26; i++) { + for (int j = 0; j < m; j++) { + store[j, i] = m + 1; + } + } + + store[m - 1, t[m - 1] - 'a'] = m - 1; + + for (int i = m - 2; i >= 0; i--) { + for (int c = 0; c < 26; c++) { + store[i, c] = store[i + 1, c]; + } + store[i, t[i] - 'a'] = i; + } + + int iPtr = 0, jPtr = 0; + while (iPtr < n && jPtr < m) { + jPtr = store[jPtr, s[iPtr] - 'a'] + 1; + if (jPtr > m) return false; + iPtr++; + } + + return iPtr == n; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/matrix-diagonal-sum.md b/articles/matrix-diagonal-sum.md index 8524ff1a7..423a6d82a 100644 --- a/articles/matrix-diagonal-sum.md +++ b/articles/matrix-diagonal-sum.md @@ -101,6 +101,33 @@ class Solution { } ``` +```csharp +public class Solution { + public int DiagonalSum(int[][] mat) { + int n = mat.Length; + + int Helper(int[][] matrix) { + int res = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i == j) { + res += matrix[i][j]; + } + } + Array.Reverse(matrix[i]); + } + return res; + } + + int sum = Helper(mat) + Helper(mat); + if ((n & 1) == 1) { + sum -= mat[n / 2][n / 2]; + } + return sum; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -176,6 +203,26 @@ class Solution { } ``` +```csharp +public class Solution { + public int DiagonalSum(int[][] mat) { + int res = 0; + int n = mat.Length; + + for (int r = 0; r < n; r++) { + res += mat[r][r]; + res += mat[r][n - r - 1]; + } + + if ((n & 1) == 1) { + res -= mat[n / 2][n / 2]; + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/maximum-nesting-depth-of-the-parentheses.md b/articles/maximum-nesting-depth-of-the-parentheses.md index f18d24a7f..72517b35c 100644 --- a/articles/maximum-nesting-depth-of-the-parentheses.md +++ b/articles/maximum-nesting-depth-of-the-parentheses.md @@ -112,6 +112,34 @@ class Solution { } ``` +```csharp +public class Solution { + public int MaxDepth(string s) { + int res = 0; + + int Dfs(int i) { + if (i == s.Length) { + return 0; + } + + int cur = Dfs(i + 1); + if (s[i] == '(') { + cur += 1; + } + else if (s[i] == ')') { + cur -= 1; + } + + res = Math.Max(res, Math.Abs(cur)); + return cur; + } + + Dfs(0); + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -205,6 +233,27 @@ class Solution { } ``` +```csharp +public class Solution { + public int MaxDepth(string s) { + int res = 0; + Stack stack = new Stack(); + + foreach (char c in s) { + if (c == '(') { + stack.Push(c); + res = Math.Max(res, stack.Count); + } + else if (c == ')') { + stack.Pop(); + } + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -297,6 +346,27 @@ class Solution { } ``` +```csharp +public class Solution { + public int MaxDepth(string s) { + int res = 0; + int cur = 0; + + foreach (char c in s) { + if (c == '(') { + cur++; + } + else if (c == ')') { + cur--; + } + res = Math.Max(res, cur); + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/maximum-number-of-points-with-cost.md b/articles/maximum-number-of-points-with-cost.md new file mode 100644 index 000000000..9eb2dd62b --- /dev/null +++ b/articles/maximum-number-of-points-with-cost.md @@ -0,0 +1,630 @@ +## 1. Recursion + +::tabs-start + +```python +class Solution: + def maxPoints(self, points: List[List[int]]) -> int: + m, n = len(points), len(points[0]) + + def dfs(r, c): + if r == m - 1: + return 0 + + res = 0 + for col in range(n): + res = max(res, points[r + 1][col] - abs(col - c) + dfs(r + 1, col)) + return res + + ans = 0 + for c in range(n): + ans = max(ans, points[0][c] + dfs(0, c)) + return ans +``` + +```java +public class Solution { + int m, n; + int[][] points; + + long dfs(int r, int c) { + if (r == m - 1) return 0; + long res = 0; + for (int col = 0; col < n; col++) { + res = Math.max(res, points[r + 1][col] - Math.abs(col - c) + dfs(r + 1, col)); + } + return res; + } + + public long maxPoints(int[][] points) { + this.m = points.length; + this.n = points[0].length; + this.points = points; + long ans = 0; + for (int c = 0; c < n; c++) { + ans = Math.max(ans, points[0][c] + dfs(0, c)); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int m, n; + vector> points; + + long long dfs(int r, int c) { + if (r == m - 1) return 0; + long long res = 0; + for (int col = 0; col < n; col++) { + res = max(res, points[r + 1][col] - abs(col - c) + dfs(r + 1, col)); + } + return res; + } + + long long maxPoints(vector>& points) { + this->points = points; + m = points.size(); + n = points[0].size(); + long long ans = 0; + for (int c = 0; c < n; c++) { + ans = max(ans, points[0][c] + dfs(0, c)); + } + return ans; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} points + * @return {number} + */ + maxPoints(points) { + let m = points.length, n = points[0].length; + + function dfs(r, c) { + if (r === m - 1) return 0; + let res = 0; + for (let col = 0; col < n; col++) { + res = Math.max(res, points[r + 1][col] - Math.abs(col - c) + dfs(r + 1, col)); + } + return res; + } + + let ans = 0; + for (let c = 0; c < n; c++) { + ans = Math.max(ans, points[0][c] + dfs(0, c)); + } + return ans; + } +} +``` + +```csharp +public class Solution { + int m, n; + int[][] points; + + long Dfs(int r, int c) { + if (r == m - 1) return 0; + long res = 0; + for (int col = 0; col < n; col++) { + res = Math.Max(res, points[r + 1][col] - Math.Abs(col - c) + Dfs(r + 1, col)); + } + return res; + } + + public long MaxPoints(int[][] points) { + this.points = points; + m = points.Length; + n = points[0].Length; + long ans = 0; + for (int c = 0; c < n; c++) { + ans = Math.Max(ans, points[0][c] + Dfs(0, c)); + } + return ans; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n ^ m)$ +* Space complexity: $O(m)$ for recursion stack. + +> Where $m$ is the number of rows, and $n$ is the number of columns. + +--- + +## 2. Dynamic Programming (Top-Down) + +::tabs-start + +```python +class Solution: + def maxPoints(self, points: List[List[int]]) -> int: + m, n = len(points), len(points[0]) + memo = {} + + def dfs(r, c): + if (r, c) in memo: + return memo[(r, c)] + if r == m - 1: + return 0 + + res = 0 + for col in range(n): + res = max(res, points[r + 1][col] - abs(col - c) + dfs(r + 1, col)) + + memo[(r, c)] = res + return res + + ans = 0 + for c in range(n): + ans = max(ans, points[0][c] + dfs(0, c)) + return ans +``` + +```java +class Solution { + int m, n; + int[][] points; + Long[][] memo; + + long dfs(int r, int c) { + if (memo[r][c] != null) return memo[r][c]; + if (r == m - 1) return 0; + + long res = 0; + for (int col = 0; col < n; col++) { + res = Math.max(res, points[r + 1][col] - Math.abs(col - c) + dfs(r + 1, col)); + } + return memo[r][c] = res; + } + + public long maxPoints(int[][] points) { + this.points = points; + m = points.length; + n = points[0].length; + memo = new Long[m][n]; + long ans = 0; + for (int c = 0; c < n; c++) { + ans = Math.max(ans, points[0][c] + dfs(0, c)); + } + return ans; + } +} +``` + +```cpp +class Solution { +public: + int m, n; + vector> points; + vector> memo; + + long long dfs(int r, int c) { + if (memo[r][c] != -1) return memo[r][c]; + if (r == m - 1) return 0; + + long long res = 0; + for (int col = 0; col < n; col++) { + res = max(res, (long long)points[r + 1][col] - abs(col - c) + dfs(r + 1, col)); + } + return memo[r][c] = res; + } + + long long maxPoints(vector>& points) { + this->points = points; + m = points.size(); + n = points[0].size(); + memo.assign(m, vector(n, -1)); + long long ans = 0; + for (int c = 0; c < n; c++) { + ans = max(ans, (long long)points[0][c] + dfs(0, c)); + } + return ans; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} points + * @return {number} + */ + maxPoints(points) { + let m = points.length, n = points[0].length; + let memo = {}; + + function dfs(r, c) { + let key = r + "," + c; + if (key in memo) return memo[key]; + if (r === m - 1) return 0; + + let res = 0; + for (let col = 0; col < n; col++) { + res = Math.max(res, points[r + 1][col] - Math.abs(col - c) + dfs(r + 1, col)); + } + return memo[key] = res; + } + + let ans = 0; + for (let c = 0; c < n; c++) { + ans = Math.max(ans, points[0][c] + dfs(0, c)); + } + return ans; + } +} +``` + +```csharp +public class Solution { + int m, n; + int[][] points; + long[,] memo; + + long Dfs(int r, int c) { + if (memo[r, c] != -1) return memo[r, c]; + if (r == m - 1) return 0; + + long res = 0; + for (int col = 0; col < n; col++) { + res = Math.Max(res, points[r + 1][col] - Math.Abs(col - c) + Dfs(r + 1, col)); + } + memo[r, c] = res; + return res; + } + + public long MaxPoints(int[][] points) { + this.points = points; + m = points.Length; + n = points[0].Length; + memo = new long[m, n]; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + memo[i, j] = -1; + } + } + long ans = 0; + for (int c = 0; c < n; c++) { + ans = Math.Max(ans, points[0][c] + Dfs(0, c)); + } + return ans; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(m * n ^ 2)$ +* Space complexity: $O(n)$ + +> Where $m$ is the number of rows, and $n$ is the number of columns. + +--- + +## 3. Dynamic Programming (Bottom-Up) + +::tabs-start + +```python +class Solution: + def maxPoints(self, points: List[List[int]]) -> int: + ROWS, COLS = len(points), len(points[0]) + dp = points[0] + + for r in range(1, ROWS): + left = [0] * COLS + left[0] = dp[0] + for c in range(1, COLS): + left[c] = max(dp[c], left[c - 1] - 1) + + right = [0] * COLS + right[COLS - 1] = dp[COLS - 1] + for c in range(COLS - 2, -1, -1): + right[c] = max(dp[c], right[c + 1] - 1) + + nextDp = points[r][:] + for c in range(COLS): + nextDp[c] += max(left[c], right[c]) + + dp = nextDp + + return max(dp) +``` + +```java +public class Solution { + public long maxPoints(int[][] points) { + int ROWS = points.length, COLS = points[0].length; + long[] dp = new long[COLS]; + for (int c = 0; c < COLS; c++) dp[c] = points[0][c]; + + for (int r = 1; r < ROWS; r++) { + long[] left = new long[COLS]; + left[0] = dp[0]; + for (int c = 1; c < COLS; c++) + left[c] = Math.max(dp[c], left[c - 1] - 1); + + long[] right = new long[COLS]; + right[COLS - 1] = dp[COLS - 1]; + for (int c = COLS - 2; c >= 0; c--) + right[c] = Math.max(dp[c], right[c + 1] - 1); + + long[] nextDp = new long[COLS]; + for (int c = 0; c < COLS; c++) + nextDp[c] = points[r][c] + Math.max(left[c], right[c]); + + dp = nextDp; + } + + long ans = 0; + for (long val : dp) ans = Math.max(ans, val); + return ans; + } +} +``` + +```cpp +class Solution { +public: + long long maxPoints(vector>& points) { + int ROWS = points.size(), COLS = points[0].size(); + vector dp(points[0].begin(), points[0].end()); + + for (int r = 1; r < ROWS; r++) { + vector left(COLS), right(COLS); + left[0] = dp[0]; + for (int c = 1; c < COLS; c++) + left[c] = max(dp[c], left[c - 1] - 1); + + right[COLS - 1] = dp[COLS - 1]; + for (int c = COLS - 2; c >= 0; c--) + right[c] = max(dp[c], right[c + 1] - 1); + + vector nextDp(COLS); + for (int c = 0; c < COLS; c++) + nextDp[c] = points[r][c] + max(left[c], right[c]); + + dp = move(nextDp); + } + + return *max_element(dp.begin(), dp.end()); + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} points + * @return {number} + */ + maxPoints(points) { + let ROWS = points.length, COLS = points[0].length; + let dp = [...points[0]]; + + for (let r = 1; r < ROWS; r++) { + let left = Array(COLS).fill(0); + left[0] = dp[0]; + for (let c = 1; c < COLS; c++) + left[c] = Math.max(dp[c], left[c - 1] - 1); + + let right = Array(COLS).fill(0); + right[COLS - 1] = dp[COLS - 1]; + for (let c = COLS - 2; c >= 0; c--) + right[c] = Math.max(dp[c], right[c + 1] - 1); + + let nextDp = [...points[r]]; + for (let c = 0; c < COLS; c++) + nextDp[c] += Math.max(left[c], right[c]); + + dp = nextDp; + } + + return Math.max(...dp); + } +} +``` + +```csharp +public class Solution { + public long MaxPoints(int[][] points) { + int ROWS = points.Length, COLS = points[0].Length; + long[] dp = new long[COLS]; + for (int c = 0; c < COLS; c++) dp[c] = points[0][c]; + + for (int r = 1; r < ROWS; r++) { + long[] left = new long[COLS]; + left[0] = dp[0]; + for (int c = 1; c < COLS; c++) + left[c] = Math.Max(dp[c], left[c - 1] - 1); + + long[] right = new long[COLS]; + right[COLS - 1] = dp[COLS - 1]; + for (int c = COLS - 2; c >= 0; c--) + right[c] = Math.Max(dp[c], right[c + 1] - 1); + + long[] nextDp = new long[COLS]; + for (int c = 0; c < COLS; c++) + nextDp[c] = points[r][c] + Math.Max(left[c], right[c]); + + dp = nextDp; + } + + long ans = 0; + foreach (long val in dp) ans = Math.Max(ans, val); + return ans; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(m * n)$ +* Space complexity: $O(n)$ + +> Where $m$ is the number of rows, and $n$ is the number of columns. + +--- + +## 4. Dynamic Programming (Space Optimized) + +::tabs-start + +```python +class Solution: + def maxPoints(self, points: List[List[int]]) -> int: + ROWS, COLS = len(points), len(points[0]) + prev = points[0] + + for r in range(1, ROWS): + cur = [0] * COLS + cur[0] = prev[0] + for c in range(1, COLS): + cur[c] = max(prev[c], cur[c - 1] - 1) + + rightMax = prev[COLS - 1] + for c in range(COLS - 2, -1 , -1): + rightMax = max(prev[c], rightMax - 1) + cur[c] = max(cur[c], rightMax) + points[r][c] + + cur[COLS - 1] += points[r][COLS - 1] + prev = cur + + return max(prev) +``` + +```java +public class Solution { + public long maxPoints(int[][] points) { + int rows = points.length, cols = points[0].length; + long[] prev = new long[cols]; + for (int c = 0; c < cols; c++) prev[c] = points[0][c]; + + for (int r = 1; r < rows; r++) { + long[] cur = new long[cols]; + cur[0] = prev[0]; + for (int c = 1; c < cols; c++) + cur[c] = Math.max(prev[c], cur[c - 1] - 1); + + long rightMax = prev[cols - 1]; + for (int c = cols - 2; c >= 0; c--) { + rightMax = Math.max(prev[c], rightMax - 1); + cur[c] = Math.max(cur[c], rightMax) + points[r][c]; + } + cur[cols - 1] += points[r][cols - 1]; + prev = cur; + } + + long ans = 0; + for (long val : prev) ans = Math.max(ans, val); + return ans; + } +} +``` + +```cpp +class Solution { +public: + long long maxPoints(vector>& points) { + int rows = points.size(), cols = points[0].size(); + vector prev(cols); + for (int c = 0; c < cols; c++) prev[c] = points[0][c]; + + for (int r = 1; r < rows; r++) { + vector cur(cols); + cur[0] = prev[0]; + for (int c = 1; c < cols; c++) + cur[c] = max(prev[c], cur[c - 1] - 1); + + long long rightMax = prev[cols - 1]; + for (int c = cols - 2; c >= 0; c--) { + rightMax = max(prev[c], rightMax - 1); + cur[c] = max(cur[c], rightMax) + points[r][c]; + } + cur[cols - 1] += points[r][cols - 1]; + prev = cur; + } + return *max_element(prev.begin(), prev.end()); + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} points + * @return {number} + */ + maxPoints(points) { + let rows = points.length, cols = points[0].length; + let prev = points[0].map(v => v); + + for (let r = 1; r < rows; r++) { + let cur = Array(cols).fill(0); + cur[0] = prev[0]; + for (let c = 1; c < cols; c++) + cur[c] = Math.max(prev[c], cur[c - 1] - 1); + + let rightMax = prev[cols - 1]; + for (let c = cols - 2; c >= 0; c--) { + rightMax = Math.max(prev[c], rightMax - 1); + cur[c] = Math.max(cur[c], rightMax) + points[r][c]; + } + cur[cols - 1] += points[r][cols - 1]; + prev = cur; + } + return Math.max(...prev); + } +} +``` + +```csharp +public class Solution { + public long MaxPoints(int[][] points) { + int rows = points.Length, cols = points[0].Length; + long[] prev = new long[cols]; + for (int c = 0; c < cols; c++) prev[c] = points[0][c]; + + for (int r = 1; r < rows; r++) { + long[] cur = new long[cols]; + cur[0] = prev[0]; + for (int c = 1; c < cols; c++) + cur[c] = Math.Max(prev[c], cur[c - 1] - 1); + + long rightMax = prev[cols - 1]; + for (int c = cols - 2; c >= 0; c--) { + rightMax = Math.Max(prev[c], rightMax - 1); + cur[c] = Math.Max(cur[c], rightMax) + points[r][c]; + } + cur[cols - 1] += points[r][cols - 1]; + prev = cur; + } + long ans = long.MinValue; + foreach (long val in prev) ans = Math.Max(ans, val); + return ans; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(m * n)$ +* Space complexity: $O(n)$ + +> Where $m$ is the number of rows, and $n$ is the number of columns. \ No newline at end of file diff --git a/articles/maximum-odd-binary-number.md b/articles/maximum-odd-binary-number.md index 41846d673..b2b63ade0 100644 --- a/articles/maximum-odd-binary-number.md +++ b/articles/maximum-odd-binary-number.md @@ -85,6 +85,24 @@ class Solution { } ``` +```csharp +public class Solution { + public string MaximumOddBinaryNumber(string s) { + char[] arr = s.ToCharArray(); + Array.Sort(arr); + Array.Reverse(arr); + int i = arr.Length - 1; + while (i >= 0 && arr[i] == '0') { + i--; + } + char temp = arr[i]; + arr[i] = arr[arr.Length - 1]; + arr[arr.Length - 1] = temp; + return new string(arr); + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -162,6 +180,20 @@ class Solution { } ``` +```csharp +public class Solution { + public string MaximumOddBinaryNumber(string s) { + int count = 0; + foreach (char c in s) { + if (c == '1') { + count++; + } + } + return new string('1', count - 1) + new string('0', s.Length - count) + "1"; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -256,6 +288,29 @@ class Solution { } ``` +```csharp +public class Solution { + public string MaximumOddBinaryNumber(string s) { + char[] arr = s.ToCharArray(); + int left = 0; + + for (int i = 0; i < arr.Length; i++) { + if (arr[i] == '1') { + char temp = arr[i]; + arr[i] = arr[left]; + arr[left] = temp; + left++; + } + } + char t = arr[left - 1]; + arr[left - 1] = arr[arr.Length - 1]; + arr[arr.Length - 1] = t; + + return new string(arr); + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/minimum-difference-between-highest-and-lowest-of-k-scores.md b/articles/minimum-difference-between-highest-and-lowest-of-k-scores.md index de7c35615..4898d271d 100644 --- a/articles/minimum-difference-between-highest-and-lowest-of-k-scores.md +++ b/articles/minimum-difference-between-highest-and-lowest-of-k-scores.md @@ -66,6 +66,24 @@ class Solution { } ``` +```csharp +public class Solution { + public int MinimumDifference(int[] nums, int k) { + Array.Sort(nums); + int l = 0, r = k - 1; + int res = int.MaxValue; + + while (r < nums.Length) { + res = Math.Min(res, nums[r] - nums[l]); + l++; + r++; + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/minimum-number-of-moves-to-seat-everyone.md b/articles/minimum-number-of-moves-to-seat-everyone.md new file mode 100644 index 000000000..e2ed02e82 --- /dev/null +++ b/articles/minimum-number-of-moves-to-seat-everyone.md @@ -0,0 +1,403 @@ +## 1. Greedy + Sorting + +::tabs-start + +```python + +``` + +```java + +``` + +```cpp + +``` + +```javascript +class Solution { + /** + * @param {number[]} seats + * @param {number[]} students + * @return {number} + */ + minMovesToSeat(seats, students) { + + } +} +``` + +```csharp + +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n \log n)$ +* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. + +--- + +## 2. Counting Sort + +::tabs-start + +```python +class Solution: + def minMovesToSeat(self, seats: List[int], students: List[int]) -> int: + max_index = max(max(seats), max(students)) + 1 + count_seats = [0] * max_index + count_students = [0] * max_index + + for seat in seats: + count_seats[seat] += 1 + for student in students: + count_students[student] += 1 + + i = j = res = 0 + remain = len(seats) + while remain: + if count_seats[i] == 0: + i += 1 + if count_students[j] == 0: + j += 1 + if count_seats[i] and count_students[j]: + res += abs(i - j) + count_seats[i] -= 1 + count_students[j] -= 1 + remain -= 1 + return res +``` + +```java +public class Solution { + public int minMovesToSeat(int[] seats, int[] students) { + int max_index = 0; + for (int s : seats) max_index = Math.max(max_index, s); + for (int s : students) max_index = Math.max(max_index, s); + max_index++; + + int[] count_seats = new int[max_index]; + int[] count_students = new int[max_index]; + + for (int seat : seats) count_seats[seat]++; + for (int student : students) count_students[student]++; + + int i = 0, j = 0, res = 0, remain = seats.length; + while (remain > 0) { + if (count_seats[i] == 0) { + i++; + continue; + } + if (count_students[j] == 0) { + j++; + continue; + } + res += Math.abs(i - j); + count_seats[i]--; + count_students[j]--; + remain--; + } + return res; + } +} +``` + +```cpp +class Solution { +public: + int minMovesToSeat(vector& seats, vector& students) { + int max_index = 0; + for (int s : seats) max_index = max(max_index, s); + for (int s : students) max_index = max(max_index, s); + max_index++; + + vector count_seats(max_index, 0); + vector count_students(max_index, 0); + + for (int seat : seats) count_seats[seat]++; + for (int student : students) count_students[student]++; + + int i = 0, j = 0, res = 0, remain = seats.size(); + while (remain > 0) { + if (count_seats[i] == 0) { + i++; + continue; + } + if (count_students[j] == 0) { + j++; + continue; + } + res += abs(i - j); + count_seats[i]--; + count_students[j]--; + remain--; + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} seats + * @param {number[]} students + * @return {number} + */ + minMovesToSeat(seats, students) { + let max_index = Math.max(...seats, ...students) + 1; + let count_seats = new Array(max_index).fill(0); + let count_students = new Array(max_index).fill(0); + + for (let seat of seats) count_seats[seat]++; + for (let student of students) count_students[student]++; + + let i = 0, j = 0, res = 0, remain = seats.length; + while (remain > 0) { + if (count_seats[i] === 0) { + i++; + continue; + } + if (count_students[j] === 0) { + j++; + continue; + } + res += Math.abs(i - j); + count_seats[i]--; + count_students[j]--; + remain--; + } + return res; + } +} +``` + +```csharp +public class Solution { + public int MinMovesToSeat(int[] seats, int[] students) { + int max_index = 0; + foreach (int s in seats) max_index = Math.Max(max_index, s); + foreach (int s in students) max_index = Math.Max(max_index, s); + max_index++; + + int[] count_seats = new int[max_index]; + int[] count_students = new int[max_index]; + + foreach (int seat in seats) count_seats[seat]++; + foreach (int student in students) count_students[student]++; + + int i = 0, j = 0, res = 0, remain = seats.Length; + while (remain > 0) { + if (count_seats[i] == 0) { + i++; + continue; + } + if (count_students[j] == 0) { + j++; + continue; + } + res += Math.Abs(i - j); + count_seats[i]--; + count_students[j]--; + remain--; + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n + m1 + m2)$ +* Space complexity: $O(m1 + m2)$ + +> Where $n$ is the size of the input arrays, $m1$ is the maximum value in the array $seats$, and $m2$ is the maximum value in the array $students$. + +--- + +## 3. Counting Sort (Optimal) + +::tabs-start + +```python +class Solution: + def minMovesToSeat(self, seats: List[int], students: List[int]) -> int: + count_seats = [0] * (max(seats) + 1) + count_students = [0] * (max(students) + 1) + + def count_sort(arr, count): + for num in arr: + count[num] += 1 + + count_sort(seats, count_seats) + count_sort(students, count_students) + + remain = len(seats) + i = j = res = 0 + while remain: + if count_seats[i] == 0: + i += 1 + if count_students[j] == 0: + j += 1 + if count_seats[i] and count_students[j]: + tmp = min(count_seats[i], count_students[j]) + res += abs(i - j) * tmp + count_seats[i] -= tmp + count_students[j] -= tmp + remain -= tmp + return res +``` + +```java +public class Solution { + public int minMovesToSeat(int[] seats, int[] students) { + int maxSeat = 0, maxStudent = 0; + for (int s : seats) maxSeat = Math.max(maxSeat, s); + for (int s : students) maxStudent = Math.max(maxStudent, s); + + int[] count_seats = new int[maxSeat + 1]; + int[] count_students = new int[maxStudent + 1]; + + for (int s : seats) count_seats[s]++; + for (int s : students) count_students[s]++; + + int remain = seats.length, i = 0, j = 0, res = 0; + while (remain > 0) { + if (count_seats[i] == 0) { + i++; + continue; + } + if (count_students[j] == 0) { + j++; + continue; + } + int tmp = Math.min(count_seats[i], count_students[j]); + res += Math.abs(i - j) * tmp; + count_seats[i] -= tmp; + count_students[j] -= tmp; + remain -= tmp; + } + return res; + } +} +``` + +```cpp +class Solution { +public: + int minMovesToSeat(vector& seats, vector& students) { + int maxSeat = *max_element(seats.begin(), seats.end()); + int maxStudent = *max_element(students.begin(), students.end()); + + vector count_seats(maxSeat + 1, 0); + vector count_students(maxStudent + 1, 0); + + for (int s : seats) count_seats[s]++; + for (int s : students) count_students[s]++; + + int remain = seats.size(), i = 0, j = 0, res = 0; + while (remain > 0) { + if (count_seats[i] == 0) { + i++; + continue; + } + if (count_students[j] == 0) { + j++; + continue; + } + int tmp = min(count_seats[i], count_students[j]); + res += abs(i - j) * tmp; + count_seats[i] -= tmp; + count_students[j] -= tmp; + remain -= tmp; + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} seats + * @param {number[]} students + * @return {number} + */ + minMovesToSeat(seats, students) { + let maxSeat = Math.max(...seats); + let maxStudent = Math.max(...students); + + let count_seats = new Array(maxSeat + 1).fill(0); + let count_students = new Array(maxStudent + 1).fill(0); + + for (let s of seats) count_seats[s]++; + for (let s of students) count_students[s]++; + + let remain = seats.length, i = 0, j = 0, res = 0; + while (remain > 0) { + if (count_seats[i] === 0) { + i++; + continue; + } + if (count_students[j] === 0) { + j++; + continue; + } + let tmp = Math.min(count_seats[i], count_students[j]); + res += Math.abs(i - j) * tmp; + count_seats[i] -= tmp; + count_students[j] -= tmp; + remain -= tmp; + } + return res; + } +} +``` + +```csharp +public class Solution { + public int MinMovesToSeat(int[] seats, int[] students) { + int maxSeat = 0, maxStudent = 0; + foreach (int s in seats) maxSeat = Math.Max(maxSeat, s); + foreach (int s in students) maxStudent = Math.Max(maxStudent, s); + + int[] count_seats = new int[maxSeat + 1]; + int[] count_students = new int[maxStudent + 1]; + + foreach (int s in seats) count_seats[s]++; + foreach (int s in students) count_students[s]++; + + int remain = seats.Length, i = 0, j = 0, res = 0; + while (remain > 0) { + if (count_seats[i] == 0) { + i++; + continue; + } + if (count_students[j] == 0) { + j++; + continue; + } + int tmp = Math.Min(count_seats[i], count_students[j]); + res += Math.Abs(i - j) * tmp; + count_seats[i] -= tmp; + count_students[j] -= tmp; + remain -= tmp; + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n + m1 + m2)$ +* Space complexity: $O(m1 + m2)$ + +> Where $n$ is the size of the input arrays, $m1$ is the maximum value in the array $seats$, and $m2$ is the maximum value in the array $students$. \ No newline at end of file diff --git a/articles/minimum-recolors-to-get-k-consecutive-black-blocks.md b/articles/minimum-recolors-to-get-k-consecutive-black-blocks.md new file mode 100644 index 000000000..29e674c7f --- /dev/null +++ b/articles/minimum-recolors-to-get-k-consecutive-black-blocks.md @@ -0,0 +1,240 @@ +## 1. Brute Force + +::tabs-start + +```python +class Solution: + def minimumRecolors(self, blocks: str, k: int) -> int: + res = len(blocks) + for i in range(len(blocks) - k + 1): + count_w = 0 + for j in range(i, i + k): + if blocks[j] == 'W': + count_w += 1 + res = min(res, count_w) + return res +``` + +```java +public class Solution { + public int minimumRecolors(String blocks, int k) { + int res = blocks.length(); + for (int i = 0; i <= blocks.length() - k; i++) { + int count_w = 0; + for (int j = i; j < i + k; j++) { + if (blocks.charAt(j) == 'W') { + count_w++; + } + } + res = Math.min(res, count_w); + } + return res; + } +} +``` + +```cpp +class Solution { +public: + int minimumRecolors(string blocks, int k) { + int res = blocks.length(); + for (int i = 0; i <= blocks.length() - k; i++) { + int count_w = 0; + for (int j = i; j < i + k; j++) { + if (blocks[j] == 'W') { + count_w++; + } + } + res = min(res, count_w); + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {string} blocks + * @param {number} k + * @return {number} + */ + minimumRecolors(blocks, k) { + let res = blocks.length; + for (let i = 0; i <= blocks.length - k; i++) { + let count_w = 0; + for (let j = i; j < i + k; j++) { + if (blocks[j] === 'W') { + count_w++; + } + } + res = Math.min(res, count_w); + } + return res; + } +} +``` + +```csharp +public class Solution { + public int MinimumRecolors(string blocks, int k) { + int res = blocks.Length; + for (int i = 0; i <= blocks.Length - k; i++) { + int count_w = 0; + for (int j = i; j < i + k; j++) { + if (blocks[j] == 'W') { + count_w++; + } + } + res = Math.Min(res, count_w); + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n * k)$ +* Space complexity: $O(1)$ + +--- + +## 2. Sliding Window + +::tabs-start + +```python +class Solution: + def minimumRecolors(self, blocks: str, k: int) -> int: + count_w = 0 + for i in range(k): + if blocks[i] == 'W': + count_w += 1 + + res = count_w + for i in range(k, len(blocks)): + if blocks[i - k] == 'W': + count_w -= 1 + if blocks[i] == 'W': + count_w += 1 + res = min(res, count_w) + return res +``` + +```java +public class Solution { + public int minimumRecolors(String blocks, int k) { + int count_w = 0; + for (int i = 0; i < k; i++) { + if (blocks.charAt(i) == 'W') { + count_w++; + } + } + + int res = count_w; + for (int i = k; i < blocks.length(); i++) { + if (blocks.charAt(i - k) == 'W') { + count_w--; + } + if (blocks.charAt(i) == 'W') { + count_w++; + } + res = Math.min(res, count_w); + } + return res; + } +} +``` + +```cpp +class Solution { +public: + int minimumRecolors(string blocks, int k) { + int count_w = 0; + for (int i = 0; i < k; i++) { + if (blocks[i] == 'W') { + count_w++; + } + } + + int res = count_w; + for (int i = k; i < blocks.size(); i++) { + if (blocks[i - k] == 'W') { + count_w--; + } + if (blocks[i] == 'W') { + count_w++; + } + res = min(res, count_w); + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {string} blocks + * @param {number} k + * @return {number} + */ + minimumRecolors(blocks, k) { + let count_w = 0; + for (let i = 0; i < k; i++) { + if (blocks[i] === 'W') { + count_w++; + } + } + + let res = count_w; + for (let i = k; i < blocks.length; i++) { + if (blocks[i - k] === 'W') { + count_w--; + } + if (blocks[i] === 'W') { + count_w++; + } + res = Math.min(res, count_w); + } + + return res; + } +} +``` + +```csharp +public class Solution { + public int MinimumRecolors(string blocks, int k) { + int count_w = 0; + for (int i = 0; i < k; i++) { + if (blocks[i] == 'W') { + count_w++; + } + } + + int res = count_w; + for (int i = k; i < blocks.Length; i++) { + if (blocks[i - k] == 'W') { + count_w--; + } + if (blocks[i] == 'W') { + count_w++; + } + res = Math.Min(res, count_w); + } + + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ \ No newline at end of file diff --git a/articles/n-ary-tree-postorder-traversal.md b/articles/n-ary-tree-postorder-traversal.md new file mode 100644 index 000000000..e2c1d2f13 --- /dev/null +++ b/articles/n-ary-tree-postorder-traversal.md @@ -0,0 +1,405 @@ +## 1. Depth First Search + +::tabs-start + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None): + self.val = val + self.children = children +""" + +class Solution: + def postorder(self, root: 'Node') -> List[int]: + res = [] + + def dfs(node): + if not node: + return + + for child in node.children: + dfs(child) + res.append(node.val) + + dfs(root) + return res +``` + +```java +/* +// Definition for a Node. +class Node { + public int val; + public List children; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, List _children) { + val = _val; + children = _children; + } +} +*/ + +public class Solution { + public List postorder(Node root) { + List res = new ArrayList<>(); + + dfs(root, res); + return res; + } + + private void dfs(Node node, List res) { + if (node == null) { + return; + } + for (Node child : node.children) { + dfs(child, res); + } + res.add(node.val); + } +} +``` + +```cpp +/* +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { +public: + vector postorder(Node* root) { + vector res; + dfs(root, res); + return res; + } + + void dfs(Node* node, vector& res) { + if (!node) return; + for (auto child : node->children) { + dfs(child, res); + } + res.push_back(node->val); + } +}; +``` + +```javascript +/** + * Definition for a binary tree node. + * class Node { + * constructor(val = 0, children = []) { + * this.val = val; + * this.children = children; + * } + * } + */ +class Solution { + /** + * @param {Node|null} root + * @return {number[]} + */ + postorder(root) { + const res = []; + + const dfs = (node) => { + if (!node) return; + for (let child of node.children) { + dfs(child); + } + res.push(node.val); + }; + + dfs(root); + return res; + } +} +``` + +```csharp +/* +// Definition for a Node. +public class Node { + public int val; + public List children; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, IList _children) { + val = _val; + children = _children; + } +} +*/ + +public class Solution { + public List Postorder(Node root) { + List res = new List(); + Dfs(root, res); + return res; + } + + private void Dfs(Node node, List res) { + if (node == null) return; + foreach (var child in node.children) { + Dfs(child, res); + } + res.Add(node.val); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(n)$ for the recursion stack. + +--- + +## 2. Iterative DFS + +::tabs-start + +```python +""" +# Definition for a Node. +class Node: + def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None): + self.val = val + self.children = children +""" + +class Solution: + def postorder(self, root: 'Node') -> List[int]: + res = [] + if not root: + return res + + stack = [(root, False)] + while stack: + node, visited = stack.pop() + if visited: + res.append(node.val) + else: + stack.append((node, True)) + for child in reversed(node.children): + stack.append((child, False)) + return res +``` + +```java +/* +// Definition for a Node. +class Node { + public int val; + public List children; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, List _children) { + val = _val; + children = _children; + } +} +*/ + +public class Solution { + public List postorder(Node root) { + List res = new ArrayList<>(); + if (root == null) return res; + + Stack> stack = new Stack<>(); + stack.push(new Pair<>(root, false)); + + while (!stack.isEmpty()) { + Pair p = stack.pop(); + Node node = p.getKey(); + boolean visited = p.getValue(); + + if (visited) { + res.add(node.val); + } else { + stack.push(new Pair<>(node, true)); + for (int i = node.children.size() - 1; i >= 0; i--) { + stack.push(new Pair<>(node.children.get(i), false)); + } + } + } + + return res; + } +} +``` + +```cpp +/* +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val) { + val = _val; + } + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ + +class Solution { +public: + vector postorder(Node* root) { + vector res; + if (!root) return res; + + stack> st; + st.push({root, false}); + + while (!st.empty()) { + auto [node, visited] = st.top(); + st.pop(); + + if (visited) { + res.push_back(node->val); + } else { + st.push({node, true}); + for (int i = (int)node->children.size() - 1; i >= 0; i--) { + st.push({node->children[i], false}); + } + } + } + + return res; + } +}; +``` + +```javascript +/** + * Definition for a binary tree node. + * class Node { + * constructor(val = 0, children = []) { + * this.val = val; + * this.children = children; + * } + * } + */ +class Solution { + /** + * @param {Node|null} root + * @return {number[]} + */ + postorder(root) { + const res = []; + if (!root) return res; + + const stack = [[root, false]]; + + while (stack.length) { + const [node, visited] = stack.pop(); + + if (visited) { + res.push(node.val); + } else { + stack.push([node, true]); + for (let i = node.children.length - 1; i >= 0; i--) { + stack.push([node.children[i], false]); + } + } + } + + return res; + } +} +``` + +```csharp +/* +// Definition for a Node. +public class Node { + public int val; + public List children; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, IList _children) { + val = _val; + children = _children; + } +} +*/ + +public class Solution { + public List Postorder(Node root) { + List res = new List(); + if (root == null) return res; + + Stack<(Node, bool)> stack = new Stack<(Node, bool)>(); + stack.Push((root, false)); + + while (stack.Count > 0) { + var (node, visited) = stack.Pop(); + + if (visited) { + res.Add(node.val); + } else { + stack.Push((node, true)); + for (int i = node.children.Count - 1; i >= 0; i--) { + stack.Push((node.children[i], false)); + } + } + } + + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(n)$ \ No newline at end of file diff --git a/articles/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.md b/articles/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.md index f99cc6f13..062ab0dde 100644 --- a/articles/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.md +++ b/articles/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.md @@ -87,6 +87,29 @@ class Solution { } ``` +```csharp +public class Solution { + public int NumOfSubarrays(int[] arr, int k, int threshold) { + int res = 0; + int l = 0; + + for (int r = k - 1; r < arr.Length; r++) { + int sum = 0; + for (int i = l; i <= r; i++) { + sum += arr[i]; + } + + if (sum / k >= threshold) { + res++; + } + l++; + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -189,6 +212,28 @@ class Solution { } ``` +```csharp +public class Solution { + public int NumOfSubarrays(int[] arr, int k, int threshold) { + int[] prefixSum = new int[arr.Length + 1]; + for (int i = 0; i < arr.Length; i++) { + prefixSum[i + 1] = prefixSum[i] + arr[i]; + } + + int res = 0, l = 0; + for (int r = k - 1; r < arr.Length; r++) { + int sum = prefixSum[r + 1] - prefixSum[l]; + if (sum / k >= threshold) { + res++; + } + l++; + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -293,6 +338,29 @@ class Solution { } ``` +```csharp +public class Solution { + public int NumOfSubarrays(int[] arr, int k, int threshold) { + int res = 0; + int curSum = 0; + + for (int i = 0; i < k - 1; i++) { + curSum += arr[i]; + } + + for (int L = 0; L <= arr.Length - k; L++) { + curSum += arr[L + k - 1]; + if (curSum / k >= threshold) { + res++; + } + curSum -= arr[L]; + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -388,6 +456,27 @@ class Solution { } ``` +```csharp +public class Solution { + public int NumOfSubarrays(int[] arr, int k, int threshold) { + threshold *= k; + int res = 0, curSum = 0; + + for (int r = 0; r < arr.Length; r++) { + curSum += arr[r]; + if (r >= k - 1) { + if (curSum >= threshold) { + res++; + } + curSum -= arr[r - k + 1]; + } + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/palindrome-linked-list.md b/articles/palindrome-linked-list.md index f4f73b7bc..069770879 100644 --- a/articles/palindrome-linked-list.md +++ b/articles/palindrome-linked-list.md @@ -132,6 +132,40 @@ class Solution { } ``` +```csharp +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +public class Solution { + public bool IsPalindrome(ListNode head) { + List arr = new List(); + ListNode cur = head; + while (cur != null) { + arr.Add(cur.val); + cur = cur.next; + } + + int l = 0, r = arr.Count - 1; + while (l < r) { + if (arr[l] != arr[r]) { + return false; + } + l++; + r--; + } + + return true; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -272,6 +306,40 @@ class Solution { } ``` +```csharp +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +public class Solution { + private ListNode cur; + + public bool IsPalindrome(ListNode head) { + cur = head; + return Rec(head); + } + + private bool Rec(ListNode node) { + if (node != null) { + if (!Rec(node.next)) { + return false; + } + if (cur.val != node.val) { + return false; + } + cur = cur.next; + } + return true; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -405,6 +473,37 @@ class Solution { } ``` +```csharp +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +public class Solution { + public bool IsPalindrome(ListNode head) { + Stack stack = new Stack(); + ListNode cur = head; + + while (cur != null) { + stack.Push(cur.val); + cur = cur.next; + } + + cur = head; + while (cur != null && cur.val == stack.Pop()) { + cur = cur.next; + } + + return cur == null; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -592,6 +691,48 @@ class Solution { } ``` +```csharp +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +public class Solution { + public bool IsPalindrome(ListNode head) { + ListNode fast = head, slow = head; + + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + } + + ListNode prev = null; + while (slow != null) { + ListNode tmp = slow.next; + slow.next = prev; + prev = slow; + slow = tmp; + } + + ListNode left = head, right = prev; + while (right != null) { + if (left.val != right.val) { + return false; + } + left = left.next; + right = right.next; + } + + return true; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/remove-linked-list-elements.md b/articles/remove-linked-list-elements.md index 30e4a5e94..9ab3c9363 100644 --- a/articles/remove-linked-list-elements.md +++ b/articles/remove-linked-list-elements.md @@ -156,6 +156,47 @@ class Solution { } ``` +```csharp +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val = 0, ListNode next = null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode RemoveElements(ListNode head, int val) { + List arr = new List(); + ListNode cur = head; + + while (cur != null) { + if (cur.val != val) { + arr.Add(cur.val); + } + cur = cur.next; + } + + if (arr.Count == 0) { + return null; + } + + ListNode res = new ListNode(arr[0]); + cur = res; + for (int i = 1; i < arr.Count; i++) { + ListNode node = new ListNode(arr[i]); + cur.next = node; + cur = cur.next; + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -248,6 +289,29 @@ class Solution { } ``` +```csharp +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode RemoveElements(ListNode head, int val) { + if (head == null) { + return null; + } + head.next = RemoveElements(head.next, val); + return head.val != val ? head : head.next; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -381,6 +445,38 @@ class Solution { } ``` +```csharp +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode RemoveElements(ListNode head, int val) { + ListNode dummy = new ListNode(0, head); + ListNode prev = dummy, curr = head; + + while (curr != null) { + ListNode nxt = curr.next; + if (curr.val == val) { + prev.next = nxt; + } else { + prev = curr; + } + curr = nxt; + } + + return dummy.next; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -506,6 +602,36 @@ class Solution { } ``` +```csharp +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode RemoveElements(ListNode head, int val) { + ListNode dummy = new ListNode(-1, head); + ListNode curr = dummy; + + while (curr.next != null) { + if (curr.next.val == val) { + curr.next = curr.next.next; + } else { + curr = curr.next; + } + } + + return dummy.next; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/replace-elements-with-greatest-element-on-right-side.md b/articles/replace-elements-with-greatest-element-on-right-side.md index 1825436a7..f69668e61 100644 --- a/articles/replace-elements-with-greatest-element-on-right-side.md +++ b/articles/replace-elements-with-greatest-element-on-right-side.md @@ -71,6 +71,23 @@ class Solution { } ``` +```csharp +public class Solution { + public int[] ReplaceElements(int[] arr) { + int n = arr.Length; + int[] ans = new int[n]; + for (int i = 0; i < n; i++) { + int rightMax = -1; + for (int j = i + 1; j < n; j++) { + rightMax = Math.Max(rightMax, arr[j]); + } + ans[i] = rightMax; + } + return ans; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -146,6 +163,21 @@ class Solution { } ``` +```csharp +public class Solution { + public int[] ReplaceElements(int[] arr) { + int n = arr.Length; + int[] ans = new int[n]; + int rightMax = -1; + for (int i = n - 1; i >= 0; i--) { + ans[i] = rightMax; + rightMax = Math.Max(arr[i], rightMax); + } + return ans; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/score-of-a-string.md b/articles/score-of-a-string.md index 9a5bf9bdf..da5d706f1 100644 --- a/articles/score-of-a-string.md +++ b/articles/score-of-a-string.md @@ -52,6 +52,18 @@ class Solution { } ``` +```csharp +public class Solution { + public int ScoreOfString(string s) { + int res = 0; + for (int i = 0; i < s.Length - 1; i++) { + res += Math.Abs(s[i] - s[i + 1]); + } + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/single-number-iii.md b/articles/single-number-iii.md index 5e714092d..c681494a6 100644 --- a/articles/single-number-iii.md +++ b/articles/single-number-iii.md @@ -111,6 +111,33 @@ class Solution { } ``` +```csharp +public class Solution { + public int[] SingleNumber(int[] nums) { + int n = nums.Length; + List res = new List(); + + for (int i = 0; i < n; i++) { + bool flag = true; + for (int j = 0; j < n; j++) { + if (i != j && nums[i] == nums[j]) { + flag = false; + break; + } + } + if (flag) { + res.Add(nums[i]); + if (res.Count == 2) { + break; + } + } + } + + return new int[] { res[0], res[1] }; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -199,6 +226,30 @@ class Solution { } ``` +```csharp +public class Solution { + public int[] SingleNumber(int[] nums) { + Dictionary count = new Dictionary(); + foreach (int num in nums) { + if (count.ContainsKey(num)) { + count[num]++; + } else { + count[num] = 1; + } + } + + List res = new List(); + foreach (var key in count.Keys) { + if (count[key] == 1) { + res.Add(key); + } + } + + return new int[] { res[0], res[1] }; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -286,6 +337,29 @@ class Solution { } ``` +```csharp +public class Solution { + public int[] SingleNumber(int[] nums) { + HashSet seen = new HashSet(); + foreach (int num in nums) { + if (seen.Contains(num)) { + seen.Remove(num); + } else { + seen.Add(num); + } + } + + int[] res = new int[2]; + int index = 0; + foreach (int num in seen) { + res[index++] = num; + } + + return res; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -379,6 +453,26 @@ class Solution { } ``` +```csharp +public class Solution { + public int[] SingleNumber(int[] nums) { + Array.Sort(nums); + List res = new List(); + int n = nums.Length; + + for (int i = 0; i < n; i++) { + if ((i > 0 && nums[i] == nums[i - 1]) || + (i + 1 < n && nums[i] == nums[i + 1])) { + continue; + } + res.Add(nums[i]); + } + + return res.ToArray(); + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -495,6 +589,33 @@ class Solution { } ``` +```csharp +public class Solution { + public int[] SingleNumber(int[] nums) { + int xor = 0; + foreach (int num in nums) { + xor ^= num; + } + + int diffBit = 1; + while ((xor & diffBit) == 0) { + diffBit <<= 1; + } + + int a = 0, b = 0; + foreach (int num in nums) { + if ((num & diffBit) != 0) { + a ^= num; + } else { + b ^= num; + } + } + + return new int[] { a, b }; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -600,6 +721,30 @@ class Solution { } ``` +```csharp +public class Solution { + public int[] SingleNumber(int[] nums) { + int xor = 0; + foreach (int num in nums) { + xor ^= num; + } + + int diffBit = xor & -xor; + + int a = 0, b = 0; + foreach (int num in nums) { + if ((num & diffBit) != 0) { + a ^= num; + } else { + b ^= num; + } + } + + return new int[] { a, b }; + } +} +``` + ::tabs-end ### Time & Space Complexity diff --git a/articles/take-gifts-from-the-richest-pile.md b/articles/take-gifts-from-the-richest-pile.md new file mode 100644 index 000000000..7e5a63926 --- /dev/null +++ b/articles/take-gifts-from-the-richest-pile.md @@ -0,0 +1,225 @@ +## 1. Simulation + +::tabs-start + +```python +class Solution: + def pickGifts(self, gifts: List[int], k: int) -> int: + for _ in range(k): + maxIdx = 0 + for i in range(1, len(gifts)): + if gifts[i] > gifts[maxIdx]: + maxIdx = i + gifts[maxIdx] = int(sqrt(gifts[maxIdx])) + return sum(gifts) +``` + +```java +public class Solution { + public long pickGifts(int[] gifts, int k) { + for (int t = 0; t < k; t++) { + int maxIdx = 0; + for (int i = 1; i < gifts.length; i++) { + if (gifts[i] > gifts[maxIdx]) { + maxIdx = i; + } + } + gifts[maxIdx] = (int) Math.floor(Math.sqrt(gifts[maxIdx])); + } + + long sum = 0; + for (int g : gifts) sum += g; + return sum; + } +} +``` + +```cpp +class Solution { +public: + long long pickGifts(vector& gifts, int k) { + for (int t = 0; t < k; t++) { + int maxIdx = 0; + for (int i = 1; i < gifts.size(); i++) { + if (gifts[i] > gifts[maxIdx]) { + maxIdx = i; + } + } + gifts[maxIdx] = floor(sqrt(gifts[maxIdx])); + } + + long long sum = 0; + for (int g : gifts) sum += g; + return sum; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} gifts + * @param {number} k + * @return {number} + */ + pickGifts(gifts, k) { + for (let t = 0; t < k; t++) { + let maxIdx = 0; + for (let i = 1; i < gifts.length; i++) { + if (gifts[i] > gifts[maxIdx]) { + maxIdx = i; + } + } + gifts[maxIdx] = Math.floor(Math.sqrt(gifts[maxIdx])); + } + + return gifts.reduce((a, b) => a + b, 0); + } +} +``` + +```csharp +public class Solution { + public long PickGifts(int[] gifts, int k) { + for (int t = 0; t < k; t++) { + int maxIdx = 0; + for (int i = 1; i < gifts.Length; i++) { + if (gifts[i] > gifts[maxIdx]) { + maxIdx = i; + } + } + gifts[maxIdx] = (int)Math.Floor(Math.Sqrt(gifts[maxIdx])); + } + + long sum = 0; + foreach (var g in gifts) sum += g; + return sum; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n * k)$ +* Space complexity: $O(1)$ extra space. + +> Where $n$ is the size of input array, $k$ is the number of seconds. + +--- + +## 2. Max-Heap + +::tabs-start + +```python +class Solution: + def pickGifts(self, gifts: List[int], k: int) -> int: + for i in range(len(gifts)): + gifts[i] = -gifts[i] + heapq.heapify(gifts) + + for _ in range(k): + n = -heapq.heappop(gifts) + heapq.heappush(gifts, -floor(sqrt(n))) + + return -sum(gifts) +``` + +```java +public class Solution { + public long pickGifts(int[] gifts, int k) { + PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder()); + for (int g : gifts) pq.offer(g); + + for (int t = 0; t < k; t++) { + int n = pq.poll(); + pq.offer((int) Math.floor(Math.sqrt(n))); + } + + long sum = 0; + while (!pq.isEmpty()) sum += pq.poll(); + return sum; + } +} +``` + +```cpp +class Solution { +public: + long long pickGifts(vector& gifts, int k) { + priority_queue pq(gifts.begin(), gifts.end()); + + for (int t = 0; t < k; t++) { + int n = pq.top(); pq.pop(); + pq.push((int)floor(sqrt(n))); + } + + long long sum = 0; + while (!pq.empty()) { + sum += pq.top(); pq.pop(); + } + return sum; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} gifts + * @param {number} k + * @return {number} + */ + pickGifts(gifts, k) { + const pq = new MaxPriorityQueue(); + gifts.forEach(g => pq.enqueue(g)); + + for (let t = 0; t < k; t++) { + const n = pq.dequeue(); + pq.enqueue(Math.floor(Math.sqrt(n))); + } + + let sum = 0; + while (!pq.isEmpty()) { + sum += pq.dequeue(); + } + return sum; + } +} +``` + +```csharp +public class Solution { + public long PickGifts(int[] gifts, int k) { + var pq = new PriorityQueue(); + + foreach (var g in gifts) { + pq.Enqueue(g, -g); + } + + for (int t = 0; t < k; t++) { + int n = pq.Dequeue(); + pq.Enqueue((int)Math.Floor(Math.Sqrt(n)), -(int)Math.Floor(Math.Sqrt(n))); + } + + long sum = 0; + while (pq.Count > 0) { + sum += pq.Dequeue(); + } + return sum; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: + - $O(n + k \log n)$ in Python. + - $O(n \log n + k \log n)$ in other languages. +* Space complexity: $O(n)$ + +> Where $n$ is the size of input array, $k$ is the number of seconds. \ No newline at end of file diff --git a/articles/valid-perfect-square.md b/articles/valid-perfect-square.md index c5682c5d4..2a4d879c5 100644 --- a/articles/valid-perfect-square.md +++ b/articles/valid-perfect-square.md @@ -69,6 +69,23 @@ class Solution { } ``` +```csharp +public class Solution { + public bool IsPerfectSquare(int num) { + for (long i = 1; i <= num; i++) { + long sq = i * i; + if (sq > num) { + return false; + } + if (sq == num) { + return true; + } + } + return false; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -121,6 +138,15 @@ class Solution { } ``` +```csharp +public class Solution { + public bool IsPerfectSquare(int num) { + int sqRoot = (int)Math.Sqrt(num); + return sqRoot * sqRoot == num; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -223,6 +249,28 @@ class Solution { } ``` +```csharp +public class Solution { + public bool IsPerfectSquare(int num) { + long l = 1, r = num; + + while (l <= r) { + long m = l + (r - l) / 2; + long sq = m * m; + if (sq > num) { + r = m - 1; + } else if (sq < num) { + l = m + 1; + } else { + return true; + } + } + + return false; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -290,6 +338,19 @@ class Solution { } ``` +```csharp +public class Solution { + public bool IsPerfectSquare(int num) { + int i = 1; + while (num > 0) { + num -= i; + i += 2; + } + return num == 0; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -353,6 +414,18 @@ class Solution { } ``` +```csharp +public class Solution { + public bool IsPerfectSquare(int num) { + long r = num; + while (r * r > num) { + r = (r + num / r) / 2; + } + return r * r == num; + } +} +``` + ::tabs-end ### Time & Space Complexity @@ -439,6 +512,24 @@ class Solution { } ``` +```csharp +public class Solution { + public bool IsPerfectSquare(int num) { + int r = 0, mask = 1 << 15; + + while (mask > 0) { + r |= mask; + if (r > (num / r)) { + r ^= mask; + } + mask >>= 1; + } + + return r * r == num; + } +} +``` + ::tabs-end ### Time & Space Complexity