Skip to content

Commit 0e48286

Browse files
authoredDec 18, 2023
feat: add solutions to lc problems: No.1600+ (doocs#2119)
1 parent 3d74b5a commit 0e48286

File tree

41 files changed

+478
-27
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+478
-27
lines changed
 

‎solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ nums[3] + nums[0] = 3 + 1 = 4.
8080

8181
可以发现,这实际上是在对一个连续区间内的元素进行加减操作,因此我们可以使用差分数组来实现。
8282

83-
时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `nums` 的长度。
83+
时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 $nums$ 的长度。
8484

8585
<!-- tabs:start -->
8686

‎solution/1600-1699/1674.Minimum Moves to Make Array Complementary/README_EN.md

+24
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,30 @@ Therefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary.
5252

5353
## Solutions
5454

55+
**Solution 1: Difference Array**
56+
57+
Let's denote $a$ as the smaller value between $nums[i]$ and $nums[n-i-1]$, and $b$ as the larger value between $nums[i]$ and $nums[n-i-1]$.
58+
59+
Suppose that after replacement, the sum of the two numbers is $x$. From the problem, we know that the minimum value of $x$ is $2$, which means both numbers are replaced by $1$; the maximum value is $2 \times limit$, which means both numbers are replaced by $limit$. Therefore, the range of $x$ is $[2,... 2 \times limit]$.
60+
61+
How to find the minimum number of replacements for different $x$?
62+
63+
We analyze and find:
64+
65+
- If $x = a + b$, then the number of replacements we need is $0$, which means the current pair of numbers already meets the complement requirement;
66+
- Otherwise, if $1 + a \le x \le limit + b $, then the number of replacements we need is $1$, which means we can replace one of the numbers;
67+
- Otherwise, if $2 \le x \le 2 \times limit$, then the number of replacements we need is $2$, which means we need to replace both numbers.
68+
69+
Therefore, we can iterate over each pair of numbers and perform the following operations:
70+
71+
1. First, add $2$ to the number of operations required in the range $[2,... 2 \times limit]$.
72+
1. Then, subtract $1$ from the number of operations required in the range $[1 + a,... limit + b]$.
73+
1. Finally, subtract $1$ from the number of operations required in the range $[a + b,... a + b]$.
74+
75+
We can see that this is actually adding and subtracting elements in a continuous interval, so we can use a difference array to implement it.
76+
77+
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$.
78+
5579
<!-- tabs:start -->
5680

5781
### **Python3**

0 commit comments

Comments
 (0)
Please sign in to comment.