Skip to content

Commit a2b5f5e

Browse files
Add solution and explanation for problem 3652: Best Time to Buy and Sell Stock using Strategy
1 parent e70407f commit a2b5f5e

File tree

12 files changed

+317
-280
lines changed

12 files changed

+317
-280
lines changed

explanations/3652/en.md

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
## Explanation
2+
3+
### Strategy (The "Why")
4+
5+
**Restate the problem:** We are given a binary string and can perform two types of operations: flip all characters from index 0 to i (cost: i+1) or flip all characters from index i to n-1 (cost: n-i). We need to find the minimum cost to make all characters equal.
6+
7+
**1.1 Constraints & Complexity:**
8+
9+
- **Input Size:** The string length n can be up to 10^5, and each character is either '0' or '1'.
10+
- **Time Complexity:** O(n) - we iterate through the string once to find all transitions.
11+
- **Space Complexity:** O(1) - we only use a constant amount of extra space.
12+
- **Edge Case:** If the string already has all characters equal, there are no transitions and the cost is 0.
13+
14+
**1.2 High-level approach:**
15+
16+
The goal is to find the minimum cost to eliminate all transitions (places where adjacent characters differ) in the string. When we encounter a transition, we can either flip the prefix or the suffix, and we choose the cheaper option.
17+
18+
![String transitions visualization](https://assets.leetcode.com/static_assets/others/string-transitions.png)
19+
20+
**1.3 Brute force vs. optimized strategy:**
21+
22+
- **Brute Force:** Try all possible combinations of operations, which would be exponential O(2^n) and too slow.
23+
- **Optimized Strategy:** For each transition at position i, we can either flip [0, i-1] (cost i) or flip [i, n-1] (cost n-i). We choose min(i, n-i) and sum all transition costs. This is O(n) time.
24+
- **Optimization:** By recognizing that each transition can be fixed independently with the cheaper operation, we avoid exponential search and solve in linear time.
25+
26+
**1.4 Decomposition:**
27+
28+
1. Iterate through the string from left to right.
29+
2. For each position i, check if there's a transition (s[i] != s[i-1]).
30+
3. If a transition exists, add the minimum cost (min(i, n-i)) to fix it.
31+
4. Return the total cost.
32+
33+
### Steps (The "How")
34+
35+
**2.1 Initialization & Example Setup:**
36+
37+
Let's use the example: `s = "0011"`, `n = 4`.
38+
39+
- Initialize `res = 0` to track total cost.
40+
- The string has one transition at position 2 (between '0' and '1').
41+
42+
**2.2 Start Checking:**
43+
44+
We iterate through the string starting from index 1, comparing each character with the previous one.
45+
46+
**2.3 Trace Walkthrough:**
47+
48+
| Position i | s[i] | s[i-1] | Transition? | Cost Option 1 (flip prefix) | Cost Option 2 (flip suffix) | Chosen Cost | res |
49+
|------------|------|--------|-------------|---------------------------|----------------------------|-------------|-----|
50+
| 1 | '0' | '0' | No | - | - | 0 | 0 |
51+
| 2 | '1' | '0' | Yes | 2 | 2 | 2 | 2 |
52+
| 3 | '1' | '1' | No | - | - | 0 | 2 |
53+
54+
**2.4 Increment and Loop:**
55+
56+
After checking all positions, we have found all transitions and calculated the minimum cost to fix each one.
57+
58+
**2.5 Return Result:**
59+
60+
The result is 2, which is the minimum cost to make all characters equal. We achieve this by flipping the suffix from index 2 to the end, changing "0011" to "0000".
61+

explanations/3769/en.md

Lines changed: 30 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -2,68 +2,60 @@
22

33
### Strategy (The "Why")
44

5-
**Restate the problem:** We need to sort integers by their binary reflection (reversing binary digits and interpreting as decimal). If two numbers have the same reflection, sort by original value.
5+
**Restate the problem:** We need to sort an array of integers in ascending order based on their binary reflection. The binary reflection of a number is obtained by reversing its binary representation (ignoring leading zeros) and interpreting it as a decimal number. If two numbers have the same binary reflection, the smaller original number should come first.
66

77
**1.1 Constraints & Complexity:**
88

9-
- **Input Size:** `1 <= nums.length <= 100`, `1 <= nums[i] <= 10^9`
10-
- **Time Complexity:** O(n log n * log max(nums)) - Sort with comparison function
11-
- **Space Complexity:** O(1) - Sorting in-place
12-
- **Edge Case:** All numbers have same reflection
9+
- **Input Size:** The array length is at most 100, and each number is between 1 and 10^9.
10+
- **Time Complexity:** O(n log n) where n is the array length - we need to sort the array, and each binary reflection calculation is O(log max_value).
11+
- **Space Complexity:** O(n) for the sorted result array.
12+
- **Edge Case:** If all numbers have the same binary reflection, they should be sorted by their original values.
1313

1414
**1.2 High-level approach:**
1515

16-
For each number, compute its binary reflection. Sort by reflection value first, then by original value if reflections are equal.
16+
The goal is to compute the binary reflection for each number and use it as the primary sort key, with the original number as the secondary sort key.
17+
18+
![Binary reflection visualization](https://assets.leetcode.com/static_assets/others/binary-reflection.png)
1719

1820
**1.3 Brute force vs. optimized strategy:**
1921

20-
- **Brute Force:** Precompute all reflections, store in separate array, sort indices. This is O(n log n) but uses extra space.
21-
- **Optimized (Custom Sort Key):** Use a key function that computes reflection on-the-fly during sorting. This is O(n log n) with O(1) extra space.
22-
- **Why it's better:** The custom key function is clean and doesn't require precomputation or extra storage.
22+
- **Brute Force:** Manually implement sorting algorithm and binary conversion, which would be more complex.
23+
- **Optimized Strategy:** Use Python's built-in `sorted()` function with a custom key function that returns (binary_reflection, original_value). This leverages efficient sorting algorithms and is O(n log n).
24+
- **Optimization:** Python's Timsort is highly optimized, and using a tuple as the sort key allows us to sort by multiple criteria efficiently.
2325

2426
**1.4 Decomposition:**
2527

26-
1. Define function to compute binary reflection
27-
2. Sort array using custom key: (reflection, original_value)
28-
3. Return sorted array
28+
1. Define a helper function to calculate binary reflection: convert to binary string, reverse it, convert back to integer.
29+
2. Sort the array using a key function that returns (binary_reflection, original_value).
30+
3. Return the sorted array.
2931

3032
### Steps (The "How")
3133

3234
**2.1 Initialization & Example Setup:**
3335

34-
Let's use the example: `nums = [4,5,4]`
35-
36-
- Binary reflections:
37-
- 4 → `100` → reversed `001` → 1
38-
- 5 → `101` → reversed `101` → 5
39-
- 4 → `100` → reversed `001` → 1
36+
Let's use the example: `nums = [4, 5, 4]`.
4037

41-
**2.2 Define Binary Reflection Function:**
38+
- Binary representations: 4 = "100", 5 = "101"
39+
- Binary reflections: 4 → "100" reversed → "001" → 1, 5 → "101" reversed → "101" → 5
4240

43-
```python
44-
def binary_reflection(n):
45-
binary = bin(n)[2:] # Remove '0b' prefix: "100"
46-
reversed_binary = binary[::-1] # "001"
47-
return int(reversed_binary, 2) # 1
48-
```
41+
**2.2 Start Processing:**
4942

50-
**2.3 Sort with Custom Key:**
43+
We compute the binary reflection for each number and sort accordingly.
5144

52-
```python
53-
return sorted(nums, key=lambda x: (binary_reflection(x), x))
54-
```
45+
**2.3 Trace Walkthrough:**
5546

56-
Sort key is `(reflection, original)`:
57-
- `(1, 4)` for first 4
58-
- `(5, 5)` for 5
59-
- `(1, 4)` for second 4
47+
| Original Number | Binary | Reversed Binary | Reflection Value | Sort Key (reflection, original) |
48+
|-----------------|--------|-----------------|------------------|----------------------------------|
49+
| 4 | "100" | "001" | 1 | (1, 4) |
50+
| 4 | "100" | "001" | 1 | (1, 4) |
51+
| 5 | "101" | "101" | 5 | (5, 5) |
6052

61-
Sorting: `(1, 4) < (1, 4) < (5, 5)``[4, 4, 5]`
53+
After sorting by (reflection, original): [(1, 4), (1, 4), (5, 5)][4, 4, 5]
6254

63-
**2.4 Return Result:**
55+
**2.4 Increment and Loop:**
6456

65-
The sorted array maintains order: same reflection values are sorted by original value.
57+
The sorting algorithm processes all elements and arranges them according to the sort keys.
6658

67-
**Time Complexity:** O(n log n * log max(nums)) - Sort with O(log max) comparison
68-
**Space Complexity:** O(1) - In-place sort
59+
**2.5 Return Result:**
6960

61+
The result is `[4, 4, 5]`, where numbers with reflection 1 (both 4s) come before the number with reflection 5, and the two 4s maintain their relative order (though they're equal).

explanations/3774/en.md

Lines changed: 30 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -2,64 +2,59 @@
22

33
### Strategy (The "Why")
44

5-
**Restate the problem:** We need to find the absolute difference between the sum of the `k` largest elements and the sum of the `k` smallest elements in the array.
5+
**Restate the problem:** We need to find the absolute difference between the sum of the k largest elements and the sum of the k smallest elements in an array.
66

77
**1.1 Constraints & Complexity:**
88

9-
- **Input Size:** `1 <= n <= 100`, `1 <= nums[i] <= 100`, `1 <= k <= n`
10-
- **Time Complexity:** O(n log n) - Sorting dominates
11-
- **Space Complexity:** O(1) - Only using input array
12-
- **Edge Case:** `k = n` means we use all elements
9+
- **Input Size:** The array length n is at most 100, and each element is between 1 and 100. k is between 1 and n.
10+
- **Time Complexity:** O(n log n) - dominated by sorting the array.
11+
- **Space Complexity:** O(n) for the sorted array.
12+
- **Edge Case:** If k equals the array length, we're comparing the sum of all elements with itself, so the difference is 0.
1313

1414
**1.2 High-level approach:**
1515

16-
Sort the array, then take the `k` largest elements (last `k` elements) and `k` smallest elements (first `k` elements). Calculate the difference between their sums.
16+
The goal is to sort the array, then calculate the sum of the first k elements (smallest) and the sum of the last k elements (largest), and return their absolute difference.
17+
18+
![Array sorting and selection visualization](https://assets.leetcode.com/static_assets/others/array-sorting.png)
1719

1820
**1.3 Brute force vs. optimized strategy:**
1921

20-
- **Brute Force:** Find k largest and k smallest without sorting, using multiple passes. This is O(n * k) time.
21-
- **Optimized (Sorting):** Sort once, then directly access first k and last k elements. This is O(n log n) time.
22-
- **Why it's better:** For small arrays (n <= 100), sorting is efficient and makes the solution simple and clear.
22+
- **Brute Force:** Find k largest and k smallest elements without sorting, which would require multiple passes and be O(n*k) time.
23+
- **Optimized Strategy:** Sort the array once in O(n log n) time, then directly access the first k and last k elements. This is simpler and efficient for the given constraints.
24+
- **Optimization:** Sorting allows us to easily identify the k smallest (first k) and k largest (last k) elements in a single operation.
2325

2426
**1.4 Decomposition:**
2527

26-
1. Sort the array in ascending order
27-
2. Sum the first `k` elements (smallest)
28-
3. Sum the last `k` elements (largest)
29-
4. Return absolute difference
28+
1. Sort the array in ascending order.
29+
2. Calculate the sum of the first k elements (smallest k).
30+
3. Calculate the sum of the last k elements (largest k).
31+
4. Return the absolute difference between these two sums.
3032

3133
### Steps (The "How")
3234

3335
**2.1 Initialization & Example Setup:**
3436

35-
Let's use the example: `nums = [5,2,2,4], k = 2`
36-
37-
- After sorting: `[2, 2, 4, 5]`
38-
39-
**2.2 Sort the Array:**
37+
Let's use the example: `nums = [5, 2, 2, 4]`, `k = 2`.
4038

41-
```python
42-
nums.sort() # [2, 2, 4, 5]
43-
```
39+
- After sorting: `sorted_nums = [2, 2, 4, 5]`
4440

45-
**2.3 Calculate Sum of k Smallest:**
41+
**2.2 Start Processing:**
4642

47-
```python
48-
sum_smallest = sum(nums[:k]) # sum([2, 2]) = 4
49-
```
43+
We calculate the sums of the smallest and largest k elements.
5044

51-
**2.4 Calculate Sum of k Largest:**
45+
**2.3 Trace Walkthrough:**
5246

53-
```python
54-
sum_largest = sum(nums[-k:]) # sum([4, 5]) = 9
55-
```
47+
| Step | Operation | Values | Result |
48+
|------|-----------|--------|--------|
49+
| 1 | Sort array | [5, 2, 2, 4] | [2, 2, 4, 5] |
50+
| 2 | Sum of k smallest | sorted_nums[:2] = [2, 2] | 2 + 2 = 4 |
51+
| 3 | Sum of k largest | sorted_nums[2:] = [4, 5] | 4 + 5 = 9 |
52+
| 4 | Absolute difference | \|9 - 4\| | 5 |
5653

57-
**2.5 Return Absolute Difference:**
54+
**2.4 Increment and Loop:**
5855

59-
```python
60-
return abs(sum_largest - sum_smallest) # abs(9 - 4) = 5
61-
```
56+
The calculation is straightforward after sorting - no loops needed for the sum calculation.
6257

63-
**Time Complexity:** O(n log n) - Sorting
64-
**Space Complexity:** O(1) - In-place sort
58+
**2.5 Return Result:**
6559

60+
The result is 5, which is the absolute difference between the sum of the 2 largest elements (9) and the sum of the 2 smallest elements (4).

explanations/3775/en.md

Lines changed: 31 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -2,76 +2,60 @@
22

33
### Strategy (The "Why")
44

5-
**Restate the problem:** We need to count vowels in the first word, then reverse each following word that has the same vowel count. Leave other words unchanged.
5+
**Restate the problem:** We need to count the vowels in the first word, then reverse each subsequent word that has the same vowel count as the first word. Words are separated by single spaces.
66

77
**1.1 Constraints & Complexity:**
88

9-
- **Input Size:** `1 <= s.length <= 10^5`
10-
- **Time Complexity:** O(n) - Single pass through string
11-
- **Space Complexity:** O(n) - Store words and result
12-
- **Edge Case:** Empty string or single word
9+
- **Input Size:** The string length can be up to 10^5 characters.
10+
- **Time Complexity:** O(n) where n is the string length - we iterate through the string once to split and process words.
11+
- **Space Complexity:** O(n) for storing the words array and result.
12+
- **Edge Case:** If there's only one word, no words need to be reversed, so we return the original string.
1313

1414
**1.2 High-level approach:**
1515

16-
Split the string into words. Count vowels in the first word. For each subsequent word, if its vowel count matches the first word's count, reverse it. Otherwise, keep it as-is.
16+
The goal is to process words sequentially: count vowels in the first word, then for each subsequent word, check if it has the same vowel count and reverse it if so.
17+
18+
![Word processing visualization](https://assets.leetcode.com/static_assets/others/word-processing.png)
1719

1820
**1.3 Brute force vs. optimized strategy:**
1921

20-
- **Brute Force:** Multiple passes - one to count vowels in first word, another to process each word. This is still O(n) but less efficient.
21-
- **Optimized (Single Pass):** Split once, count vowels in first word, then process each word in one pass. This is O(n) time.
22-
- **Why it's better:** We process the string efficiently in a single logical pass, making the code clear and maintainable.
22+
- **Brute Force:** Process each word multiple times, counting vowels separately for comparison and reversal, which would be less efficient.
23+
- **Optimized Strategy:** Split the string into words once, count vowels in the first word, then iterate through remaining words, counting vowels and reversing when needed. This is O(n) time.
24+
- **Optimization:** By processing words in a single pass and reusing the vowel counting logic, we avoid redundant operations.
2325

2426
**1.4 Decomposition:**
2527

26-
1. Split string into words
27-
2. Count vowels in first word
28-
3. For each subsequent word:
29-
- Count its vowels
30-
- If count matches first word, reverse it
31-
- Otherwise, keep as-is
32-
4. Join words back into string
28+
1. Split the string into words.
29+
2. Count vowels in the first word.
30+
3. For each subsequent word, count its vowels.
31+
4. If the vowel count matches the first word's count, reverse the word.
32+
5. Join all words back into a string.
3333

3434
### Steps (The "How")
3535

3636
**2.1 Initialization & Example Setup:**
3737

38-
Let's use the example: `s = "cat and mice"`
39-
40-
- Words: `["cat", "and", "mice"]`
41-
- Vowels: `{'a', 'e', 'i', 'o', 'u'}`
42-
43-
**2.2 Split into Words:**
44-
45-
```python
46-
words = s.split() # ["cat", "and", "mice"]
47-
```
38+
Let's use the example: `s = "cat and mice"`.
4839

49-
**2.3 Count Vowels in First Word:**
40+
- Words: ["cat", "and", "mice"]
41+
- First word: "cat" has 1 vowel ('a')
5042

51-
```python
52-
first_vowel_count = sum(1 for c in words[0] if c in vowels) # "cat" has 1 vowel: 'a'
53-
```
43+
**2.2 Start Processing:**
5444

55-
**2.4 Process Each Subsequent Word:**
45+
We process each word after the first one, checking vowel counts and reversing when needed.
5646

57-
```python
58-
for word in words[1:]:
59-
vowel_count = sum(1 for c in word if c in vowels)
60-
if vowel_count == first_vowel_count:
61-
res.append(word[::-1]) # Reverse
62-
else:
63-
res.append(word) # Keep as-is
64-
```
47+
**2.3 Trace Walkthrough:**
6548

66-
For `"and"`: vowel_count = 1 (matches), so reverse → `"dna"`
67-
For `"mice"`: vowel_count = 2 (doesn't match), so keep → `"mice"`
49+
| Word | Vowel Count | Matches First? | Action | Result |
50+
|------|-------------|----------------|--------|--------|
51+
| "cat" | 1 | - | Keep as is | "cat" |
52+
| "and" | 1 | Yes | Reverse | "dna" |
53+
| "mice" | 2 | No | Keep as is | "mice" |
6854

69-
**2.5 Join and Return:**
55+
**2.4 Increment and Loop:**
7056

71-
```python
72-
return ' '.join(res) # "cat dna mice"
73-
```
57+
After processing all words, we join them with spaces.
7458

75-
**Time Complexity:** O(n) - Process each character once
76-
**Space Complexity:** O(n) - Store words and result
59+
**2.5 Return Result:**
7760

61+
The result is `"cat dna mice"`, where "and" (1 vowel) was reversed to "dna" because it matches the first word's vowel count, while "mice" (2 vowels) remained unchanged.

0 commit comments

Comments
 (0)