diff --git a/solution/1400-1499/1471.The k Strongest Values in an Array/README.md b/solution/1400-1499/1471.The k Strongest Values in an Array/README.md index aff9091de0ada..7b555fe591284 100644 --- a/solution/1400-1499/1471.The k Strongest Values in an Array/README.md +++ b/solution/1400-1499/1471.The k Strongest Values in an Array/README.md @@ -90,9 +90,13 @@ tags: -### 方法一:自定义排序 +### 方法一:排序 -时间复杂度 $O(2nlogn)$。 +我们首先对数组 $\textit{arr}$ 进行排序,然后找到数组的中位数 $m$。 + +接下来,我们按照题目描述的规则对数组进行排序,最后返回数组的前 $k$ 个元素即可。 + +时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $\textit{arr}$ 的长度。 @@ -174,6 +178,16 @@ func abs(x int) int { } ``` +#### TypeScript + +```ts +function getStrongest(arr: number[], k: number): number[] { + arr.sort((a, b) => a - b); + const m = arr[(arr.length - 1) >> 1]; + return arr.sort((a, b) => Math.abs(b - m) - Math.abs(a - m) || b - a).slice(0, k); +} +``` + diff --git a/solution/1400-1499/1471.The k Strongest Values in an Array/README_EN.md b/solution/1400-1499/1471.The k Strongest Values in an Array/README_EN.md index f4b65f8b482ae..86f888133c43d 100644 --- a/solution/1400-1499/1471.The k Strongest Values in an Array/README_EN.md +++ b/solution/1400-1499/1471.The k Strongest Values in an Array/README_EN.md @@ -76,7 +76,13 @@ Any permutation of [11,8,6,6,7] is accepted. -### Solution 1 +### Solution 1: Sorting + +We first sort the array $\textit{arr}$ and then find the median $m$ of the array. + +Next, we sort the array according to the rules described in the problem, and finally return the first $k$ elements of the array. + +The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\textit{arr}$. @@ -158,6 +164,16 @@ func abs(x int) int { } ``` +#### TypeScript + +```ts +function getStrongest(arr: number[], k: number): number[] { + arr.sort((a, b) => a - b); + const m = arr[(arr.length - 1) >> 1]; + return arr.sort((a, b) => Math.abs(b - m) - Math.abs(a - m) || b - a).slice(0, k); +} +``` + diff --git a/solution/1400-1499/1471.The k Strongest Values in an Array/Solution.ts b/solution/1400-1499/1471.The k Strongest Values in an Array/Solution.ts new file mode 100644 index 0000000000000..a6a27c0596b7a --- /dev/null +++ b/solution/1400-1499/1471.The k Strongest Values in an Array/Solution.ts @@ -0,0 +1,5 @@ +function getStrongest(arr: number[], k: number): number[] { + arr.sort((a, b) => a - b); + const m = arr[(arr.length - 1) >> 1]; + return arr.sort((a, b) => Math.abs(b - m) - Math.abs(a - m) || b - a).slice(0, k); +} diff --git a/solution/1400-1499/1472.Design Browser History/README.md b/solution/1400-1499/1472.Design Browser History/README.md index b11b988129cd2..c3574fdefd6ae 100644 --- a/solution/1400-1499/1472.Design Browser History/README.md +++ b/solution/1400-1499/1472.Design Browser History/README.md @@ -76,9 +76,17 @@ browserHistory.back(7); // 你原本在浏览 "google.com -### 方法一:栈 +### 方法一:双栈 -使用两个栈模拟前进与后退操作。 +我们可以使用两个栈 $\textit{stk1}$ 和 $\textit{stk2}$ 分别存储浏览后退页面和前进页面。初始时 $\textit{stk1}$ 包含 $\textit{homepage}$,而 $\textit{stk2}$ 为空。 + +调用 $\text{visit}(url)$ 时,我们将 $\textit{url}$ 加入 $\textit{stk1}$,并清空 $\textit{stk2}$。时间复杂度 $O(1)$。 + +调用 $\text{back}(steps)$ 时,我们将 $\textit{stk1}$ 的栈顶元素弹出并加入 $\textit{stk2}$,重复这一操作 $steps$ 次,直到 $\textit{stk1}$ 的长度为 $1$ 或者 $steps$ 为 $0$。最后返回 $\textit{stk1}$ 的栈顶元素。时间复杂度 $O(\textit{steps})$。 + +调用 $\text{forward}(steps)$ 时,我们将 $\textit{stk2}$ 的栈顶元素弹出并加入 $\textit{stk1}$,重复这一操作 $steps$ 次,直到 $\textit{stk2}$ 为空或者 $steps$ 为 $0$。最后返回 $\textit{stk1}$ 的栈顶元素。时间复杂度 $O(\textit{steps})$。 + +空间复杂度 $O(n)$,其中 $n$ 是浏览历史记录的长度。 diff --git a/solution/1400-1499/1472.Design Browser History/README_EN.md b/solution/1400-1499/1472.Design Browser History/README_EN.md index 6e123e6f91752..422e736ed9c0f 100644 --- a/solution/1400-1499/1472.Design Browser History/README_EN.md +++ b/solution/1400-1499/1472.Design Browser History/README_EN.md @@ -75,7 +75,17 @@ browserHistory.back(7); // You are in "google.com", -### Solution 1 +### Solution 1: Two Stacks + +We can use two stacks, $\textit{stk1}$ and $\textit{stk2}$, to store the back and forward pages, respectively. Initially, $\textit{stk1}$ contains the $\textit{homepage}$, and $\textit{stk2}$ is empty. + +When calling $\text{visit}(url)$, we add $\textit{url}$ to $\textit{stk1}$ and clear $\textit{stk2}$. The time complexity is $O(1)$. + +When calling $\text{back}(steps)$, we pop the top element from $\textit{stk1}$ and push it to $\textit{stk2}$. We repeat this operation $steps$ times until the length of $\textit{stk1}$ is $1$ or $steps$ is $0$. Finally, we return the top element of $\textit{stk1}$. The time complexity is $O(\textit{steps})$. + +When calling $\text{forward}(steps)$, we pop the top element from $\textit{stk2}$ and push it to $\textit{stk1}$. We repeat this operation $steps$ times until $\textit{stk2}$ is empty or $steps$ is $0$. Finally, we return the top element of $\textit{stk1}$. The time complexity is $O(\textit{steps})$. + +The space complexity is $O(n)$, where $n$ is the length of the browsing history. diff --git a/solution/1400-1499/1473.Paint House III/README.md b/solution/1400-1499/1473.Paint House III/README.md index 7a79a23cb4795..9a5f9842fee9b 100644 --- a/solution/1400-1499/1473.Paint House III/README.md +++ b/solution/1400-1499/1473.Paint House III/README.md @@ -91,25 +91,25 @@ tags: ### 方法一:动态规划 -我们定义 $f[i][j][k]$ 表示将下标 $[0,..i]$ 的房子涂上颜色,最后一个房子的颜色为 $j$,且恰好形成 $k$ 个街区的最小花费。那么答案就是 $f[m-1][j][target]$,其中 $j$ 的取值范围为 $[1,..n]$。初始时,我们判断下标为 $0$ 的房子是否已经涂色,如果未涂色,那么 $f[0][j][1] = cost[0][j - 1]$,其中 $j \in [1,..n]$。如果已经涂色,那么 $f[0][houses[0]][1] = 0$。其他的 $f[i][j][k]$ 的值都初始化为 $\infty$。 +我们定义 $f[i][j][k]$ 表示将下标 $[0,..i]$ 的房子涂上颜色,最后一个房子的颜色为 $j$,且恰好形成 $k$ 个街区的最小花费。那么答案就是 $f[m-1][j][\textit{target}]$,其中 $j$ 的取值范围为 $[1,..n]$。初始时,我们判断下标为 $0$ 的房子是否已经涂色,如果未涂色,那么 $f[0][j][1] = \textit{cost}[0][j - 1]$,其中 $j \in [1,..n]$。如果已经涂色,那么 $f[0][\textit{houses}[0]][1] = 0$。其他的 $f[i][j][k]$ 的值都初始化为 $\infty$。 接下来,我们从下标 $i=1$ 开始遍历,对于每个 $i$,我们判断下标为 $i$ 的房子是否已经涂色: -如果未涂色,那么我们可以将下标为 $i$ 的房子涂成颜色 $j$,我们枚举街区的数量 $k$,其中 $k \in [1,..min(target, i + 1)]$,并且枚举下标为 $i$ 的房子的前一个房子的颜色 $j_0$,其中 $j_0 \in [1,..n]$,那么我们可以得到状态转移方程: +如果未涂色,那么我们可以将下标为 $i$ 的房子涂成颜色 $j$,我们枚举街区的数量 $k$,其中 $k \in [1,..\min(\textit{target}, i + 1)]$,并且枚举下标为 $i$ 的房子的前一个房子的颜色 $j_0$,其中 $j_0 \in [1,..n]$,那么我们可以得到状态转移方程: $$ -f[i][j][k] = \min_{j_0 \in [1,..n]} \{ f[i - 1][j_0][k - (j \neq j_0)] + cost[i][j - 1] \} +f[i][j][k] = \min_{j_0 \in [1,..n]} \{ f[i - 1][j_0][k - (j \neq j_0)] + \textit{cost}[i][j - 1] \} $$ -如果已经涂色,那么我们可以将下标为 $i$ 的房子涂成颜色 $j$,我们枚举街区的数量 $k$,其中 $k \in [1,..min(target, i + 1)]$,并且枚举下标为 $i$ 的房子的前一个房子的颜色 $j_0$,其中 $j_0 \in [1,..n]$,那么我们可以得到状态转移方程: +如果已经涂色,那么我们可以将下标为 $i$ 的房子涂成颜色 $j$,我们枚举街区的数量 $k$,其中 $k \in [1,..\min(\textit{target}, i + 1)]$,并且枚举下标为 $i$ 的房子的前一个房子的颜色 $j_0$,其中 $j_0 \in [1,..n]$,那么我们可以得到状态转移方程: $$ f[i][j][k] = \min_{j_0 \in [1,..n]} \{ f[i - 1][j_0][k - (j \neq j_0)] \} $$ -最后,我们返回 $f[m - 1][j][target]$,其中 $j \in [1,..n]$,如果所有的 $f[m - 1][j][target]$ 的值都为 $\infty$,那么返回 $-1$。 +最后,我们返回 $f[m - 1][j][\textit{target}]$,其中 $j \in [1,..n]$,如果所有的 $f[m - 1][j][\textit{target}]$ 的值都为 $\infty$,那么返回 $-1$。 -时间复杂度 $O(m \times n^2 \times target)$,空间复杂度 $O(m \times n \times target)$。其中 $m$, $n$, $target$ 分别为房子的数量,颜色的数量,街区的数量。 +时间复杂度 $O(m \times n^2 \times \textit{target})$,空间复杂度 $O(m \times n \times \textit{target})$。其中 $m$, $n$, $\textit{target}$ 分别为房子的数量,颜色的数量,街区的数量。 diff --git a/solution/1400-1499/1473.Paint House III/README_EN.md b/solution/1400-1499/1473.Paint House III/README_EN.md index f4a8885ba9e6e..804a5898db39a 100644 --- a/solution/1400-1499/1473.Paint House III/README_EN.md +++ b/solution/1400-1499/1473.Paint House III/README_EN.md @@ -53,7 +53,7 @@ Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9. Input: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3 Output: 11 Explanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2] -This array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. +This array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. Cost of paint the first and last house (10 + 1) = 11. @@ -84,7 +84,27 @@ Cost of paint the first and last house (10 + 1) = 11. -### Solution 1 +### Solution 1: Dynamic Programming + +We define $f[i][j][k]$ to represent the minimum cost to paint houses from index $0$ to $i$, with the last house painted in color $j$, and exactly forming $k$ blocks. The answer is $f[m-1][j][\textit{target}]$, where $j$ ranges from $1$ to $n$. Initially, we check if the house at index $0$ is already painted. If it is not painted, then $f[0][j][1] = \textit{cost}[0][j - 1]$, where $j \in [1,..n]$. If it is already painted, then $f[0][\textit{houses}[0]][1] = 0$. All other values of $f[i][j][k]$ are initialized to $\infty$. + +Next, we start iterating from index $i=1$. For each $i$, we check if the house at index $i$ is already painted: + +If it is not painted, we can paint the house at index $i$ with color $j$. We enumerate the number of blocks $k$, where $k \in [1,..\min(\textit{target}, i + 1)]$, and enumerate the color of the previous house $j_0$, where $j_0 \in [1,..n]$. Then we can derive the state transition equation: + +$$ +f[i][j][k] = \min_{j_0 \in [1,..n]} \{ f[i - 1][j_0][k - (j \neq j_0)] + \textit{cost}[i][j - 1] \} +$$ + +If it is already painted, we can paint the house at index $i$ with color $j$. We enumerate the number of blocks $k$, where $k \in [1,..\min(\textit{target}, i + 1)]$, and enumerate the color of the previous house $j_0$, where $j_0 \in [1,..n]$. Then we can derive the state transition equation: + +$$ +f[i][j][k] = \min_{j_0 \in [1,..n]} \{ f[i - 1][j_0][k - (j \neq j_0)] \} +$$ + +Finally, we return $f[m - 1][j][\textit{target}]$, where $j \in [1,..n]$. If all values of $f[m - 1][j][\textit{target}]$ are $\infty$, then return $-1$. + +The time complexity is $O(m \times n^2 \times \textit{target})$, and the space complexity is $O(m \times n \times \textit{target})$. Here, $m$, $n$, and $\textit{target}$ represent the number of houses, the number of colors, and the number of blocks, respectively. diff --git a/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README.md b/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README.md index 37cffa6267c27..4ba4da0a14b2a 100644 --- a/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README.md +++ b/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README.md @@ -86,9 +86,9 @@ tags: ### 方法一:模拟 -按照题意模拟,遍历链表,每次遍历 $m$ 个节点,然后删除 $n$ 个节点,直到链表尾部。 +我们可以模拟整个删除过程,首先用 $\textit{pre}$ 指针指向链表头部,然后遍历链表,移动 $m - 1$ 步,如果 $\textit{pre}$ 为空,说明从当前节点开始的节点个数小于 $m$,直接返回头部;否则,用 $\textit{cur}$ 指针指向 $\textit{pre}$,然后移动 $n$ 步,如果 $\textit{cur}$ 为空,说明从 $\textit{pre}$ 开始的节点个数小于 $m + n$,直接将 $\textit{pre}$ 的 $\textit{next}$ 指向 $\text{null}$;否则,将 $\textit{pre}$ 的 $\textit{next}$ 指向 $\textit{cur}$ 的 $\textit{next}$,然后将 $\textit{pre}$ 移动到 $\textit{pre}$ 的 $\textit{next}$。继续遍历链表,直到 $\textit{pre}$ 为空,返回头部。 -时间复杂度 $O(n)$,空间复杂度 $O(1)$。 +时间复杂度 $O(n)$,其中 $n$ 是链表中节点的个数。空间复杂度 $O(1)$。 @@ -222,6 +222,41 @@ func deleteNodes(head *ListNode, m int, n int) *ListNode { } ``` +#### TypeScript + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function deleteNodes(head: ListNode | null, m: number, n: number): ListNode | null { + let pre = head; + while (pre) { + for (let i = 0; i < m - 1 && pre; ++i) { + pre = pre.next; + } + if (!pre) { + break; + } + let cur = pre; + for (let i = 0; i < n && cur; ++i) { + cur = cur.next; + } + pre.next = cur?.next || null; + pre = pre.next; + } + return head; +} +``` + diff --git a/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README_EN.md b/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README_EN.md index 212b1792bb43e..43bf7da770be7 100644 --- a/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README_EN.md +++ b/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/README_EN.md @@ -67,7 +67,11 @@ Head of the linked list after removing nodes is returned. -### Solution 1 +### Solution 1: Simulation + +We can simulate the entire deletion process. First, use a pointer $\textit{pre}$ to point to the head of the linked list, then traverse the linked list, moving $m - 1$ steps. If $\textit{pre}$ is null, it means the number of nodes from the current node is less than $m$, so we directly return the head. Otherwise, use a pointer $\textit{cur}$ to point to $\textit{pre}$, then move $n$ steps. If $\textit{cur}$ is null, it means the number of nodes from $\textit{pre}$ is less than $m + n$, so we directly set the $\textit{next}$ of $\textit{pre}$ to null. Otherwise, set the $\textit{next}$ of $\textit{pre}$ to the $\textit{next}$ of $\textit{cur}$, then move $\textit{pre}$ to its $\textit{next}$. Continue traversing the linked list until $\textit{pre}$ is null, then return the head. + +The time complexity is $O(n)$, where $n$ is the number of nodes in the linked list. The space complexity is $O(1)$. @@ -201,6 +205,41 @@ func deleteNodes(head *ListNode, m int, n int) *ListNode { } ``` +#### TypeScript + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function deleteNodes(head: ListNode | null, m: number, n: number): ListNode | null { + let pre = head; + while (pre) { + for (let i = 0; i < m - 1 && pre; ++i) { + pre = pre.next; + } + if (!pre) { + break; + } + let cur = pre; + for (let i = 0; i < n && cur; ++i) { + cur = cur.next; + } + pre.next = cur?.next || null; + pre = pre.next; + } + return head; +} +``` + diff --git a/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/Solution.ts b/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/Solution.ts new file mode 100644 index 0000000000000..34d5bfcc9665c --- /dev/null +++ b/solution/1400-1499/1474.Delete N Nodes After M Nodes of a Linked List/Solution.ts @@ -0,0 +1,30 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function deleteNodes(head: ListNode | null, m: number, n: number): ListNode | null { + let pre = head; + while (pre) { + for (let i = 0; i < m - 1 && pre; ++i) { + pre = pre.next; + } + if (!pre) { + break; + } + let cur = pre; + for (let i = 0; i < n && cur; ++i) { + cur = cur.next; + } + pre.next = cur?.next || null; + pre = pre.next; + } + return head; +} diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/README.md b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/README.md index f04d06a12411b..0c7d7ca422947 100644 --- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/README.md +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/README.md @@ -67,11 +67,13 @@ tags: -### 方法一:暴力枚举 +### 方法一:单调栈 -按题意模拟,采用双重循环枚举 `i` 和 `j`。 +题目实际上是求每个元素右侧第一个比它小的元素,可以使用单调栈来解决。 -时间复杂度为 $O(n^2)$,忽略结果数组的空间消耗,空间复杂度 $O(1)$。 +我们逆序遍历数组 $\textit{prices}$,利用单调栈找出左侧最近一个比当前元素小的元素,然后计算折扣。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是数组 $\textit{prices}$ 的长度。 @@ -80,14 +82,15 @@ tags: ```python class Solution: def finalPrices(self, prices: List[int]) -> List[int]: - ans = [] - for i, v in enumerate(prices): - ans.append(v) - for j in range(i + 1, len(prices)): - if prices[j] <= v: - ans[-1] -= prices[j] - break - return ans + stk = [] + for i in reversed(range(len(prices))): + x = prices[i] + while stk and x < stk[-1]: + stk.pop() + if stk: + prices[i] -= stk[-1] + stk.append(x) + return prices ``` #### Java @@ -96,17 +99,18 @@ class Solution: class Solution { public int[] finalPrices(int[] prices) { int n = prices.length; - int[] ans = new int[n]; - for (int i = 0; i < n; ++i) { - ans[i] = prices[i]; - for (int j = i + 1; j < n; ++j) { - if (prices[j] <= prices[i]) { - ans[i] -= prices[j]; - break; - } + Deque stk = new ArrayDeque<>(); + for (int i = n - 1; i >= 0; --i) { + int x = prices[i]; + while (!stk.isEmpty() && stk.peek() > x) { + stk.pop(); + } + if (!stk.isEmpty()) { + prices[i] -= stk.peek(); } + stk.push(x); } - return ans; + return prices; } } ``` @@ -117,18 +121,18 @@ class Solution { class Solution { public: vector finalPrices(vector& prices) { - int n = prices.size(); - vector ans(n); - for (int i = 0; i < n; ++i) { - ans[i] = prices[i]; - for (int j = i + 1; j < n; ++j) { - if (prices[j] <= prices[i]) { - ans[i] -= prices[j]; - break; - } + stack stk; + for (int i = prices.size() - 1; ~i; --i) { + int x = prices[i]; + while (!stk.empty() && stk.top() > x) { + stk.pop(); } + if (!stk.empty()) { + prices[i] -= stk.top(); + } + stk.push(x); } - return ans; + return prices; } }; ``` @@ -137,18 +141,18 @@ public: ```go func finalPrices(prices []int) []int { - n := len(prices) - ans := make([]int, n) - for i, v := range prices { - ans[i] = v - for j := i + 1; j < n; j++ { - if prices[j] <= v { - ans[i] -= prices[j] - break - } + stk := []int{} + for i := len(prices) - 1; i >= 0; i-- { + x := prices[i] + for len(stk) > 0 && stk[len(stk)-1] > x { + stk = stk[:len(stk)-1] + } + if len(stk) > 0 { + prices[i] -= stk[len(stk)-1] } + stk = append(stk, x) } - return ans + return prices } ``` @@ -156,18 +160,16 @@ func finalPrices(prices []int) []int { ```ts function finalPrices(prices: number[]): number[] { - const n = prices.length; - const ans = new Array(n); - for (let i = 0; i < n; ++i) { - ans[i] = prices[i]; - for (let j = i + 1; j < n; ++j) { - if (prices[j] <= prices[i]) { - ans[i] -= prices[j]; - break; - } + const stk: number[] = []; + for (let i = prices.length - 1; ~i; --i) { + const x = prices[i]; + while (stk.length && stk.at(-1)! > x) { + stk.pop(); } + prices[i] -= stk.at(-1) || 0; + stk.push(x); } - return ans; + return prices; } ``` @@ -175,19 +177,19 @@ function finalPrices(prices: number[]): number[] { ```rust impl Solution { - pub fn final_prices(prices: Vec) -> Vec { - let n = prices.len(); - let mut stack = Vec::new(); - let mut res = vec![0; n]; - for i in (0..n).rev() { - let price = prices[i]; - while !stack.is_empty() && *stack.last().unwrap() > price { - stack.pop(); + pub fn final_prices(mut prices: Vec) -> Vec { + let mut stk: Vec = Vec::new(); + for i in (0..prices.len()).rev() { + let x = prices[i]; + while !stk.is_empty() && x < *stk.last().unwrap() { + stk.pop(); + } + if let Some(&top) = stk.last() { + prices[i] -= top; } - res[i] = price - stack.last().unwrap_or(&0); - stack.push(price); + stk.push(x); } - res + prices } } ``` @@ -200,13 +202,14 @@ impl Solution { * @return {number[]} */ var finalPrices = function (prices) { - for (let i = 0; i < prices.length; i++) { - for (let j = i + 1; j < prices.length; j++) { - if (prices[i] >= prices[j]) { - prices[i] -= prices[j]; - break; - } + const stk = []; + for (let i = prices.length - 1; ~i; --i) { + const x = prices[i]; + while (stk.length && stk.at(-1) > x) { + stk.pop(); } + prices[i] -= stk.at(-1) || 0; + stk.push(x); } return prices; }; @@ -221,244 +224,22 @@ class Solution { * @return Integer[] */ function finalPrices($prices) { - for ($i = 0; $i < count($prices); $i++) { - for ($j = $i + 1; $j < count($prices); $j++) { - if ($prices[$i] >= $prices[$j]) { - $prices[$i] -= $prices[$j]; - break; - } - } - } - return $prices; - } -} -``` - - - - - - - -### 方法二:单调栈 - -单调栈常见模型:找出每个数左/右边**离它最近的**且**比它大/小的数**。模板: - -```python -stk = [] -for i in range(n): - while stk and check(stk[-1], i): - stk.pop() - stk.append(i) -``` - -本题我们可以采用正序、逆序两种方式遍历数组 `prices`。 - -时间复杂度 $O(n)$,其中 $n$ 表示数组 `prices` 的长度。 + $stk = []; + $n = count($prices); - - -#### Python3 - -```python -class Solution: - def finalPrices(self, prices: List[int]) -> List[int]: - stk = [] - ans = prices[:] - for i, v in enumerate(prices): - while stk and prices[stk[-1]] >= v: - ans[stk.pop()] -= v - stk.append(i) - return ans -``` - -#### Java - -```java -class Solution { - public int[] finalPrices(int[] prices) { - Deque stk = new ArrayDeque<>(); - int n = prices.length; - int[] ans = new int[n]; - for (int i = 0; i < n; ++i) { - ans[i] = prices[i]; - while (!stk.isEmpty() && prices[stk.peek()] >= prices[i]) { - ans[stk.pop()] -= prices[i]; + for ($i = $n - 1; $i >= 0; $i--) { + $x = $prices[$i]; + while (!empty($stk) && $x < end($stk)) { + array_pop($stk); } - stk.push(i); - } - return ans; - } -} -``` - -#### C++ - -```cpp -class Solution { -public: - vector finalPrices(vector& prices) { - stack stk; - vector ans = prices; - for (int i = 0; i < prices.size(); ++i) { - while (!stk.empty() && prices[stk.top()] >= prices[i]) { - ans[stk.top()] -= prices[i]; - stk.pop(); + if (!empty($stk)) { + $prices[$i] -= end($stk); } - stk.push(i); + $stk[] = $x; } - return ans; - } -}; -``` - -#### Go -```go -func finalPrices(prices []int) []int { - var stk []int - n := len(prices) - ans := make([]int, n) - for i, v := range prices { - ans[i] = v - for len(stk) > 0 && prices[stk[len(stk)-1]] >= v { - ans[stk[len(stk)-1]] -= v - stk = stk[:len(stk)-1] - } - stk = append(stk, i) - } - return ans -} -``` - -#### TypeScript - -```ts -function finalPrices(prices: number[]): number[] { - const n = prices.length; - const stk = []; - const ans = new Array(n); - for (let i = 0; i < n; ++i) { - ans[i] = prices[i]; - while (stk.length && prices[stk[stk.length - 1]] >= prices[i]) { - ans[stk.pop()] -= prices[i]; - } - stk.push(i); - } - return ans; -} -``` - - - - - - - -### 方法三 - - - -#### Python3 - -```python -class Solution: - def finalPrices(self, prices: List[int]) -> List[int]: - stk = [] - ans = prices[:] - for i in range(len(prices) - 1, -1, -1): - while stk and prices[stk[-1]] > prices[i]: - stk.pop() - if stk: - ans[i] -= prices[stk[-1]] - stk.append(i) - return ans -``` - -#### Java - -```java -class Solution { - public int[] finalPrices(int[] prices) { - Deque stk = new ArrayDeque<>(); - int n = prices.length; - int[] ans = new int[n]; - for (int i = n - 1; i >= 0; --i) { - ans[i] = prices[i]; - while (!stk.isEmpty() && prices[stk.peek()] > prices[i]) { - stk.pop(); - } - if (!stk.isEmpty()) { - ans[i] -= prices[stk.peek()]; - } - stk.push(i); - } - return ans; - } -} -``` - -#### C++ - -```cpp -class Solution { -public: - vector finalPrices(vector& prices) { - stack stk; - int n = prices.size(); - vector ans(n); - for (int i = n - 1; i >= 0; --i) { - ans[i] = prices[i]; - while (!stk.empty() && prices[stk.top()] > prices[i]) { - stk.pop(); - } - if (!stk.empty()) { - ans[i] -= prices[stk.top()]; - } - stk.push(i); - } - return ans; - } -}; -``` - -#### Go - -```go -func finalPrices(prices []int) []int { - stk := []int{} - n := len(prices) - ans := make([]int, n) - for i := n - 1; i >= 0; i-- { - ans[i] = prices[i] - for len(stk) > 0 && prices[stk[len(stk)-1]] > prices[i] { - stk = stk[:len(stk)-1] - } - if len(stk) > 0 { - ans[i] -= prices[stk[len(stk)-1]] - } - stk = append(stk, i) - } - return ans -} -``` - -#### TypeScript - -```ts -function finalPrices(prices: number[]): number[] { - const n = prices.length; - const stack = []; - const res = new Array(n); - for (let i = n - 1; i >= 0; i--) { - const price = prices[i]; - while (stack.length !== 0 && stack[stack.length - 1] > price) { - stack.pop(); - } - res[i] = price - (stack[stack.length - 1] ?? 0); - stack.push(price); + return $prices; } - return res; } ``` diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/README_EN.md b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/README_EN.md index b86dea9c66387..72d7dfd45532f 100644 --- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/README_EN.md +++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/README_EN.md @@ -32,7 +32,7 @@ tags:
 Input: prices = [8,4,6,2,3]
 Output: [4,2,4,2,3]
-Explanation: 
+Explanation:
 For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4.
 For item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2.
 For item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4.
@@ -68,7 +68,13 @@ For items 3 and 4 you will not receive any discount at all.
 
 
 
-### Solution 1
+### Solution 1: Monotonic Stack
+
+The problem is essentially to find the first element on the right side that is smaller than each element. We can use a monotonic stack to solve this.
+
+We traverse the array $\textit{prices}$ in reverse order, using the monotonic stack to find the nearest smaller element on the left side of the current element, and then calculate the discount.
+
+The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of the array $\textit{prices}$.
 
 
 
@@ -77,14 +83,15 @@ For items 3 and 4 you will not receive any discount at all.
 ```python
 class Solution:
     def finalPrices(self, prices: List[int]) -> List[int]:
-        ans = []
-        for i, v in enumerate(prices):
-            ans.append(v)
-            for j in range(i + 1, len(prices)):
-                if prices[j] <= v:
-                    ans[-1] -= prices[j]
-                    break
-        return ans
+        stk = []
+        for i in reversed(range(len(prices))):
+            x = prices[i]
+            while stk and x < stk[-1]:
+                stk.pop()
+            if stk:
+                prices[i] -= stk[-1]
+            stk.append(x)
+        return prices
 ```
 
 #### Java
@@ -93,17 +100,18 @@ class Solution:
 class Solution {
     public int[] finalPrices(int[] prices) {
         int n = prices.length;
-        int[] ans = new int[n];
-        for (int i = 0; i < n; ++i) {
-            ans[i] = prices[i];
-            for (int j = i + 1; j < n; ++j) {
-                if (prices[j] <= prices[i]) {
-                    ans[i] -= prices[j];
-                    break;
-                }
+        Deque stk = new ArrayDeque<>();
+        for (int i = n - 1; i >= 0; --i) {
+            int x = prices[i];
+            while (!stk.isEmpty() && stk.peek() > x) {
+                stk.pop();
+            }
+            if (!stk.isEmpty()) {
+                prices[i] -= stk.peek();
             }
+            stk.push(x);
         }
-        return ans;
+        return prices;
     }
 }
 ```
@@ -114,18 +122,18 @@ class Solution {
 class Solution {
 public:
     vector finalPrices(vector& prices) {
-        int n = prices.size();
-        vector ans(n);
-        for (int i = 0; i < n; ++i) {
-            ans[i] = prices[i];
-            for (int j = i + 1; j < n; ++j) {
-                if (prices[j] <= prices[i]) {
-                    ans[i] -= prices[j];
-                    break;
-                }
+        stack stk;
+        for (int i = prices.size() - 1; ~i; --i) {
+            int x = prices[i];
+            while (!stk.empty() && stk.top() > x) {
+                stk.pop();
             }
+            if (!stk.empty()) {
+                prices[i] -= stk.top();
+            }
+            stk.push(x);
         }
-        return ans;
+        return prices;
     }
 };
 ```
@@ -134,18 +142,18 @@ public:
 
 ```go
 func finalPrices(prices []int) []int {
-	n := len(prices)
-	ans := make([]int, n)
-	for i, v := range prices {
-		ans[i] = v
-		for j := i + 1; j < n; j++ {
-			if prices[j] <= v {
-				ans[i] -= prices[j]
-				break
-			}
+	stk := []int{}
+	for i := len(prices) - 1; i >= 0; i-- {
+		x := prices[i]
+		for len(stk) > 0 && stk[len(stk)-1] > x {
+			stk = stk[:len(stk)-1]
+		}
+		if len(stk) > 0 {
+			prices[i] -= stk[len(stk)-1]
 		}
+		stk = append(stk, x)
 	}
-	return ans
+	return prices
 }
 ```
 
@@ -153,18 +161,16 @@ func finalPrices(prices []int) []int {
 
 ```ts
 function finalPrices(prices: number[]): number[] {
-    const n = prices.length;
-    const ans = new Array(n);
-    for (let i = 0; i < n; ++i) {
-        ans[i] = prices[i];
-        for (let j = i + 1; j < n; ++j) {
-            if (prices[j] <= prices[i]) {
-                ans[i] -= prices[j];
-                break;
-            }
+    const stk: number[] = [];
+    for (let i = prices.length - 1; ~i; --i) {
+        const x = prices[i];
+        while (stk.length && stk.at(-1)! > x) {
+            stk.pop();
         }
+        prices[i] -= stk.at(-1) || 0;
+        stk.push(x);
     }
-    return ans;
+    return prices;
 }
 ```
 
@@ -172,19 +178,19 @@ function finalPrices(prices: number[]): number[] {
 
 ```rust
 impl Solution {
-    pub fn final_prices(prices: Vec) -> Vec {
-        let n = prices.len();
-        let mut stack = Vec::new();
-        let mut res = vec![0; n];
-        for i in (0..n).rev() {
-            let price = prices[i];
-            while !stack.is_empty() && *stack.last().unwrap() > price {
-                stack.pop();
+    pub fn final_prices(mut prices: Vec) -> Vec {
+        let mut stk: Vec = Vec::new();
+        for i in (0..prices.len()).rev() {
+            let x = prices[i];
+            while !stk.is_empty() && x < *stk.last().unwrap() {
+                stk.pop();
+            }
+            if let Some(&top) = stk.last() {
+                prices[i] -= top;
             }
-            res[i] = price - stack.last().unwrap_or(&0);
-            stack.push(price);
+            stk.push(x);
         }
-        res
+        prices
     }
 }
 ```
@@ -197,13 +203,14 @@ impl Solution {
  * @return {number[]}
  */
 var finalPrices = function (prices) {
-    for (let i = 0; i < prices.length; i++) {
-        for (let j = i + 1; j < prices.length; j++) {
-            if (prices[i] >= prices[j]) {
-                prices[i] -= prices[j];
-                break;
-            }
+    const stk = [];
+    for (let i = prices.length - 1; ~i; --i) {
+        const x = prices[i];
+        while (stk.length && stk.at(-1) > x) {
+            stk.pop();
         }
+        prices[i] -= stk.at(-1) || 0;
+        stk.push(x);
     }
     return prices;
 };
@@ -218,230 +225,22 @@ class Solution {
      * @return Integer[]
      */
     function finalPrices($prices) {
-        for ($i = 0; $i < count($prices); $i++) {
-            for ($j = $i + 1; $j < count($prices); $j++) {
-                if ($prices[$i] >= $prices[$j]) {
-                    $prices[$i] -= $prices[$j];
-                    break;
-                }
-            }
-        }
-        return $prices;
-    }
-}
-```
-
-
-
-
-
-
-
-### Solution 2
-
-
-
-#### Python3
+        $stk = [];
+        $n = count($prices);
 
-```python
-class Solution:
-    def finalPrices(self, prices: List[int]) -> List[int]:
-        stk = []
-        ans = prices[:]
-        for i, v in enumerate(prices):
-            while stk and prices[stk[-1]] >= v:
-                ans[stk.pop()] -= v
-            stk.append(i)
-        return ans
-```
-
-#### Java
-
-```java
-class Solution {
-    public int[] finalPrices(int[] prices) {
-        Deque stk = new ArrayDeque<>();
-        int n = prices.length;
-        int[] ans = new int[n];
-        for (int i = 0; i < n; ++i) {
-            ans[i] = prices[i];
-            while (!stk.isEmpty() && prices[stk.peek()] >= prices[i]) {
-                ans[stk.pop()] -= prices[i];
+        for ($i = $n - 1; $i >= 0; $i--) {
+            $x = $prices[$i];
+            while (!empty($stk) && $x < end($stk)) {
+                array_pop($stk);
             }
-            stk.push(i);
-        }
-        return ans;
-    }
-}
-```
-
-#### C++
-
-```cpp
-class Solution {
-public:
-    vector finalPrices(vector& prices) {
-        stack stk;
-        vector ans = prices;
-        for (int i = 0; i < prices.size(); ++i) {
-            while (!stk.empty() && prices[stk.top()] >= prices[i]) {
-                ans[stk.top()] -= prices[i];
-                stk.pop();
+            if (!empty($stk)) {
+                $prices[$i] -= end($stk);
             }
-            stk.push(i);
+            $stk[] = $x;
         }
-        return ans;
-    }
-};
-```
-
-#### Go
-
-```go
-func finalPrices(prices []int) []int {
-	var stk []int
-	n := len(prices)
-	ans := make([]int, n)
-	for i, v := range prices {
-		ans[i] = v
-		for len(stk) > 0 && prices[stk[len(stk)-1]] >= v {
-			ans[stk[len(stk)-1]] -= v
-			stk = stk[:len(stk)-1]
-		}
-		stk = append(stk, i)
-	}
-	return ans
-}
-```
 
-#### TypeScript
-
-```ts
-function finalPrices(prices: number[]): number[] {
-    const n = prices.length;
-    const stk = [];
-    const ans = new Array(n);
-    for (let i = 0; i < n; ++i) {
-        ans[i] = prices[i];
-        while (stk.length && prices[stk[stk.length - 1]] >= prices[i]) {
-            ans[stk.pop()] -= prices[i];
-        }
-        stk.push(i);
-    }
-    return ans;
-}
-```
-
-
-
-
-
-
-
-### Solution 3
-
-
-
-#### Python3
-
-```python
-class Solution:
-    def finalPrices(self, prices: List[int]) -> List[int]:
-        stk = []
-        ans = prices[:]
-        for i in range(len(prices) - 1, -1, -1):
-            while stk and prices[stk[-1]] > prices[i]:
-                stk.pop()
-            if stk:
-                ans[i] -= prices[stk[-1]]
-            stk.append(i)
-        return ans
-```
-
-#### Java
-
-```java
-class Solution {
-    public int[] finalPrices(int[] prices) {
-        Deque stk = new ArrayDeque<>();
-        int n = prices.length;
-        int[] ans = new int[n];
-        for (int i = n - 1; i >= 0; --i) {
-            ans[i] = prices[i];
-            while (!stk.isEmpty() && prices[stk.peek()] > prices[i]) {
-                stk.pop();
-            }
-            if (!stk.isEmpty()) {
-                ans[i] -= prices[stk.peek()];
-            }
-            stk.push(i);
-        }
-        return ans;
-    }
-}
-```
-
-#### C++
-
-```cpp
-class Solution {
-public:
-    vector finalPrices(vector& prices) {
-        stack stk;
-        int n = prices.size();
-        vector ans(n);
-        for (int i = n - 1; i >= 0; --i) {
-            ans[i] = prices[i];
-            while (!stk.empty() && prices[stk.top()] > prices[i]) {
-                stk.pop();
-            }
-            if (!stk.empty()) {
-                ans[i] -= prices[stk.top()];
-            }
-            stk.push(i);
-        }
-        return ans;
-    }
-};
-```
-
-#### Go
-
-```go
-func finalPrices(prices []int) []int {
-	stk := []int{}
-	n := len(prices)
-	ans := make([]int, n)
-	for i := n - 1; i >= 0; i-- {
-		ans[i] = prices[i]
-		for len(stk) > 0 && prices[stk[len(stk)-1]] > prices[i] {
-			stk = stk[:len(stk)-1]
-		}
-		if len(stk) > 0 {
-			ans[i] -= prices[stk[len(stk)-1]]
-		}
-		stk = append(stk, i)
-	}
-	return ans
-}
-```
-
-#### TypeScript
-
-```ts
-function finalPrices(prices: number[]): number[] {
-    const n = prices.length;
-    const stack = [];
-    const res = new Array(n);
-    for (let i = n - 1; i >= 0; i--) {
-        const price = prices[i];
-        while (stack.length !== 0 && stack[stack.length - 1] > price) {
-            stack.pop();
-        }
-        res[i] = price - (stack[stack.length - 1] ?? 0);
-        stack.push(price);
+        return $prices;
     }
-    return res;
 }
 ```
 
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.cpp b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.cpp
index a27c24247cb10..b443773fc8bdd 100644
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.cpp	
+++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.cpp	
@@ -1,17 +1,17 @@
 class Solution {
 public:
     vector finalPrices(vector& prices) {
-        int n = prices.size();
-        vector ans(n);
-        for (int i = 0; i < n; ++i) {
-            ans[i] = prices[i];
-            for (int j = i + 1; j < n; ++j) {
-                if (prices[j] <= prices[i]) {
-                    ans[i] -= prices[j];
-                    break;
-                }
+        stack stk;
+        for (int i = prices.size() - 1; ~i; --i) {
+            int x = prices[i];
+            while (!stk.empty() && stk.top() > x) {
+                stk.pop();
             }
+            if (!stk.empty()) {
+                prices[i] -= stk.top();
+            }
+            stk.push(x);
         }
-        return ans;
+        return prices;
     }
-};
\ No newline at end of file
+};
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.go b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.go
index 6d9911f2dd0e4..d240432f9dea1 100644
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.go	
+++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.go	
@@ -1,14 +1,14 @@
 func finalPrices(prices []int) []int {
-	n := len(prices)
-	ans := make([]int, n)
-	for i, v := range prices {
-		ans[i] = v
-		for j := i + 1; j < n; j++ {
-			if prices[j] <= v {
-				ans[i] -= prices[j]
-				break
-			}
+	stk := []int{}
+	for i := len(prices) - 1; i >= 0; i-- {
+		x := prices[i]
+		for len(stk) > 0 && stk[len(stk)-1] > x {
+			stk = stk[:len(stk)-1]
 		}
+		if len(stk) > 0 {
+			prices[i] -= stk[len(stk)-1]
+		}
+		stk = append(stk, x)
 	}
-	return ans
-}
\ No newline at end of file
+	return prices
+}
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.java b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.java
index 1f9c12d04cea6..6fdb1d9ac8f34 100644
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.java	
+++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.java	
@@ -1,16 +1,17 @@
 class Solution {
     public int[] finalPrices(int[] prices) {
         int n = prices.length;
-        int[] ans = new int[n];
-        for (int i = 0; i < n; ++i) {
-            ans[i] = prices[i];
-            for (int j = i + 1; j < n; ++j) {
-                if (prices[j] <= prices[i]) {
-                    ans[i] -= prices[j];
-                    break;
-                }
+        Deque stk = new ArrayDeque<>();
+        for (int i = n - 1; i >= 0; --i) {
+            int x = prices[i];
+            while (!stk.isEmpty() && stk.peek() > x) {
+                stk.pop();
             }
+            if (!stk.isEmpty()) {
+                prices[i] -= stk.peek();
+            }
+            stk.push(x);
         }
-        return ans;
+        return prices;
     }
-}
\ No newline at end of file
+}
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.js b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.js
index 9eff2851ec96d..6088fbe23d290 100644
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.js	
+++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.js	
@@ -3,13 +3,14 @@
  * @return {number[]}
  */
 var finalPrices = function (prices) {
-    for (let i = 0; i < prices.length; i++) {
-        for (let j = i + 1; j < prices.length; j++) {
-            if (prices[i] >= prices[j]) {
-                prices[i] -= prices[j];
-                break;
-            }
+    const stk = [];
+    for (let i = prices.length - 1; ~i; --i) {
+        const x = prices[i];
+        while (stk.length && stk.at(-1) > x) {
+            stk.pop();
         }
+        prices[i] -= stk.at(-1) || 0;
+        stk.push(x);
     }
     return prices;
 };
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.php b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.php
index 3347b98a08557..6f913e37049eb 100644
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.php	
+++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.php	
@@ -4,14 +4,20 @@ class Solution {
      * @return Integer[]
      */
     function finalPrices($prices) {
-        for ($i = 0; $i < count($prices); $i++) {
-            for ($j = $i + 1; $j < count($prices); $j++) {
-                if ($prices[$i] >= $prices[$j]) {
-                    $prices[$i] -= $prices[$j];
-                    break;
-                }
+        $stk = [];
+        $n = count($prices);
+
+        for ($i = $n - 1; $i >= 0; $i--) {
+            $x = $prices[$i];
+            while (!empty($stk) && $x < end($stk)) {
+                array_pop($stk);
             }
+            if (!empty($stk)) {
+                $prices[$i] -= end($stk);
+            }
+            $stk[] = $x;
         }
+
         return $prices;
     }
 }
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.py b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.py
index 7942f1115c027..9d0aa3ef0c898 100644
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.py	
+++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.py	
@@ -1,10 +1,11 @@
 class Solution:
     def finalPrices(self, prices: List[int]) -> List[int]:
-        ans = []
-        for i, v in enumerate(prices):
-            ans.append(v)
-            for j in range(i + 1, len(prices)):
-                if prices[j] <= v:
-                    ans[-1] -= prices[j]
-                    break
-        return ans
+        stk = []
+        for i in reversed(range(len(prices))):
+            x = prices[i]
+            while stk and x < stk[-1]:
+                stk.pop()
+            if stk:
+                prices[i] -= stk[-1]
+            stk.append(x)
+        return prices
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.rs b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.rs
index 909993b1afbd6..85929a70c29cf 100644
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.rs	
+++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.rs	
@@ -1,16 +1,16 @@
 impl Solution {
-    pub fn final_prices(prices: Vec) -> Vec {
-        let n = prices.len();
-        let mut stack = Vec::new();
-        let mut res = vec![0; n];
-        for i in (0..n).rev() {
-            let price = prices[i];
-            while !stack.is_empty() && *stack.last().unwrap() > price {
-                stack.pop();
+    pub fn final_prices(mut prices: Vec) -> Vec {
+        let mut stk: Vec = Vec::new();
+        for i in (0..prices.len()).rev() {
+            let x = prices[i];
+            while !stk.is_empty() && x < *stk.last().unwrap() {
+                stk.pop();
             }
-            res[i] = price - stack.last().unwrap_or(&0);
-            stack.push(price);
+            if let Some(&top) = stk.last() {
+                prices[i] -= top;
+            }
+            stk.push(x);
         }
-        res
+        prices
     }
 }
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.ts b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.ts
index dfaead9442012..91a01620fcd36 100644
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.ts	
+++ b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution.ts	
@@ -1,14 +1,12 @@
 function finalPrices(prices: number[]): number[] {
-    const n = prices.length;
-    const ans = new Array(n);
-    for (let i = 0; i < n; ++i) {
-        ans[i] = prices[i];
-        for (let j = i + 1; j < n; ++j) {
-            if (prices[j] <= prices[i]) {
-                ans[i] -= prices[j];
-                break;
-            }
+    const stk: number[] = [];
+    for (let i = prices.length - 1; ~i; --i) {
+        const x = prices[i];
+        while (stk.length && stk.at(-1)! > x) {
+            stk.pop();
         }
+        prices[i] -= stk.at(-1) || 0;
+        stk.push(x);
     }
-    return ans;
+    return prices;
 }
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.cpp b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.cpp
deleted file mode 100644
index c3ffc6b6269e6..0000000000000
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.cpp	
+++ /dev/null
@@ -1,15 +0,0 @@
-class Solution {
-public:
-    vector finalPrices(vector& prices) {
-        stack stk;
-        vector ans = prices;
-        for (int i = 0; i < prices.size(); ++i) {
-            while (!stk.empty() && prices[stk.top()] >= prices[i]) {
-                ans[stk.top()] -= prices[i];
-                stk.pop();
-            }
-            stk.push(i);
-        }
-        return ans;
-    }
-};
\ No newline at end of file
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.go b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.go
deleted file mode 100644
index 45a1268ec3f07..0000000000000
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.go	
+++ /dev/null
@@ -1,14 +0,0 @@
-func finalPrices(prices []int) []int {
-	var stk []int
-	n := len(prices)
-	ans := make([]int, n)
-	for i, v := range prices {
-		ans[i] = v
-		for len(stk) > 0 && prices[stk[len(stk)-1]] >= v {
-			ans[stk[len(stk)-1]] -= v
-			stk = stk[:len(stk)-1]
-		}
-		stk = append(stk, i)
-	}
-	return ans
-}
\ No newline at end of file
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.java b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.java
deleted file mode 100644
index d921c3896b78b..0000000000000
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.java	
+++ /dev/null
@@ -1,15 +0,0 @@
-class Solution {
-    public int[] finalPrices(int[] prices) {
-        Deque stk = new ArrayDeque<>();
-        int n = prices.length;
-        int[] ans = new int[n];
-        for (int i = 0; i < n; ++i) {
-            ans[i] = prices[i];
-            while (!stk.isEmpty() && prices[stk.peek()] >= prices[i]) {
-                ans[stk.pop()] -= prices[i];
-            }
-            stk.push(i);
-        }
-        return ans;
-    }
-}
\ No newline at end of file
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.py b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.py
deleted file mode 100644
index 5b205f2d148c3..0000000000000
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.py	
+++ /dev/null
@@ -1,9 +0,0 @@
-class Solution:
-    def finalPrices(self, prices: List[int]) -> List[int]:
-        stk = []
-        ans = prices[:]
-        for i, v in enumerate(prices):
-            while stk and prices[stk[-1]] >= v:
-                ans[stk.pop()] -= v
-            stk.append(i)
-        return ans
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.ts b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.ts
deleted file mode 100644
index 8f59cd019eae0..0000000000000
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution2.ts	
+++ /dev/null
@@ -1,13 +0,0 @@
-function finalPrices(prices: number[]): number[] {
-    const n = prices.length;
-    const stk = [];
-    const ans = new Array(n);
-    for (let i = 0; i < n; ++i) {
-        ans[i] = prices[i];
-        while (stk.length && prices[stk[stk.length - 1]] >= prices[i]) {
-            ans[stk.pop()] -= prices[i];
-        }
-        stk.push(i);
-    }
-    return ans;
-}
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.cpp b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.cpp
deleted file mode 100644
index 31676616def76..0000000000000
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.cpp	
+++ /dev/null
@@ -1,19 +0,0 @@
-class Solution {
-public:
-    vector finalPrices(vector& prices) {
-        stack stk;
-        int n = prices.size();
-        vector ans(n);
-        for (int i = n - 1; i >= 0; --i) {
-            ans[i] = prices[i];
-            while (!stk.empty() && prices[stk.top()] > prices[i]) {
-                stk.pop();
-            }
-            if (!stk.empty()) {
-                ans[i] -= prices[stk.top()];
-            }
-            stk.push(i);
-        }
-        return ans;
-    }
-};
\ No newline at end of file
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.go b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.go
deleted file mode 100644
index 0e2ed7f1c6429..0000000000000
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.go	
+++ /dev/null
@@ -1,16 +0,0 @@
-func finalPrices(prices []int) []int {
-	stk := []int{}
-	n := len(prices)
-	ans := make([]int, n)
-	for i := n - 1; i >= 0; i-- {
-		ans[i] = prices[i]
-		for len(stk) > 0 && prices[stk[len(stk)-1]] > prices[i] {
-			stk = stk[:len(stk)-1]
-		}
-		if len(stk) > 0 {
-			ans[i] -= prices[stk[len(stk)-1]]
-		}
-		stk = append(stk, i)
-	}
-	return ans
-}
\ No newline at end of file
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.java b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.java
deleted file mode 100644
index bbba5ea49ba52..0000000000000
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.java	
+++ /dev/null
@@ -1,18 +0,0 @@
-class Solution {
-    public int[] finalPrices(int[] prices) {
-        Deque stk = new ArrayDeque<>();
-        int n = prices.length;
-        int[] ans = new int[n];
-        for (int i = n - 1; i >= 0; --i) {
-            ans[i] = prices[i];
-            while (!stk.isEmpty() && prices[stk.peek()] > prices[i]) {
-                stk.pop();
-            }
-            if (!stk.isEmpty()) {
-                ans[i] -= prices[stk.peek()];
-            }
-            stk.push(i);
-        }
-        return ans;
-    }
-}
\ No newline at end of file
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.py b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.py
deleted file mode 100644
index 4de446e25eb2d..0000000000000
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.py	
+++ /dev/null
@@ -1,11 +0,0 @@
-class Solution:
-    def finalPrices(self, prices: List[int]) -> List[int]:
-        stk = []
-        ans = prices[:]
-        for i in range(len(prices) - 1, -1, -1):
-            while stk and prices[stk[-1]] > prices[i]:
-                stk.pop()
-            if stk:
-                ans[i] -= prices[stk[-1]]
-            stk.append(i)
-        return ans
diff --git a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.ts b/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.ts
deleted file mode 100644
index a784c3155edea..0000000000000
--- a/solution/1400-1499/1475.Final Prices With a Special Discount in a Shop/Solution3.ts	
+++ /dev/null
@@ -1,14 +0,0 @@
-function finalPrices(prices: number[]): number[] {
-    const n = prices.length;
-    const stack = [];
-    const res = new Array(n);
-    for (let i = n - 1; i >= 0; i--) {
-        const price = prices[i];
-        while (stack.length !== 0 && stack[stack.length - 1] > price) {
-            stack.pop();
-        }
-        res[i] = price - (stack[stack.length - 1] ?? 0);
-        stack.push(price);
-    }
-    return res;
-}