Topic description
Given an array prices
, its i
element prices[i]
represents the price of a given stock on day i
You can only choose to buy the stock on a certain day , and choose to sell the stock on a different day in the future . Design an algorithm to calculate the maximum profit you can make.
Returns the maximum profit you can make from this trade. If you cannot make any profit, return 0
.
Example 1:
输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
Example 2:
输入:prices = [7,6,4,3,1]
输出:0
解释:在这种情况下, 没有交易完成, 所以最大利润为 0。
Leetcode original title address: https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/
Thought analysis
Regarding this topic, it is possible to obtain the result by brute force twice, but it is not very good. Here we will not talk about the code method of brute force solution (附在最后)
.
When we generally encounter a complex problem, we can 把复杂问题进行简化拆解
, when solving the problem of simplified disassembly, look for the law, find the law, and finally 在复杂问题上使用我们之前发现的简化问题相似的规律
, so as to solve it
For example, when the boss comes up and asks us to build an atomic bomb, ah, no. It doesn't matter, let's study first, how to make a grenade. Anyway, they’re all eggs, they’re all for explosions, and there’s always something in common. Once the grenade is made, the atomic bomb will be coming soon. This analogy is not quite right. Anyway, that's what it means. Let's experience ^_^
After reading the title, we probably know that the requirements are as follows:
To get the highest returns, you must buy low and sell high
- That is:
找到数组中的最大值,最小值,最大减最小就是最高收益
- That is:
Stocks are, buy first and sell later. So the time to buy stocks is earlier and the time to sell stocks later
- That is:
最小值的位置索引要小于最大值的位置索引
- That is:
- The problem is, we don't know for the time being that the stock that we bought was the lowest on that day and the highest on that day? ? ?
Simply, let's assume that the stock is the lowest on the first day, and you can buy it for 3 yuan, and then the stock rises and falls, but it has never been lower than 3 yuan. So buying the first day is the best deal. We bought it on a 5-day cycle and paid by credit card on the first day. So we simulate and define an array: let arr = [3,8,6,12,9]
Next, we transform the problem into:
已知第一天买的股价最低,后面的每一天都比第一天股价高,求那一天卖掉最多能赚多少钱
The simplification of dismantling complex problems
So we can write the following code according to our needs:
let arr = [3, 8, 6, 12, 9]
function maxProfit(prices) {
// 1. 假设初始收益为0,后面每一天的价格减去第一天的买入价格就是收益
let maxProfitValue = 0
for (let i = 1; i < prices.length; i++) {
// 2. 只要收益大的(收益大的记在本子上,收益小的划掉不要)
maxProfitValue = Math.max(maxProfitValue, prices[i] - 3)
}
// 3. 最终得到一个最大收益,并返回
return maxProfitValue;
}
console.log( maxProfit(arr) ); // 9
The above code maxProfitValue = Math.max(maxProfitValue, prices[i] - 3)
we can change the way of writing, because 3
is the price of the first day, so replace it with arr[0]
that is:
Simple transformation of complex problem disassembly
let arr = [3, 8, 6, 12, 9]
function maxProfit(prices) {
let min = prices[0] // 变换之~我们已知最低点股价是第一项,故定义变量表示
// 1. 假设初始收益为0,后面每一天的价格减去第一天的买入价格就是收益
let maxProfitValue = 0
for (let i = 1; i < prices.length; i++) {
// 2. 只要收益大的(收益大的记在本子上,收益小的划掉不要)
maxProfitValue = Math.max(maxProfitValue, prices[i] - min) // 变换之~最低价是min,这里卖出高价-买入最低价也是用min变量了
}
// 3. 最终得到一个最大收益,并返回
return maxProfitValue;
}
console.log( maxProfit(arr) ); // 9
Seeing this, some friends said, what if the first item in the array is not the smallest on the first day? What if the second term might be smaller than the first? It doesn't matter, let's compare it, whoever is smaller uses whoever. Anyway, there is a loop, you can get the value of each item, and the comparison is just me. The pseudo code is as follows:
let min = arr[0] // 假设第一项最小
min = Math.min(min,arr[i]) // 第二项和当下最小值做对比,谁小就保留谁
Math.min(5,2,8,3) // Math.min finds the minimum value in a set of numbers. The left code is executed to get the result 2
So the above code can do a transformation
Transformation of complex problems to solve
function maxProfit(prices) {
let min = prices[0] // 1. 假设最低股价是第一项,若后续有更低的股价,就用后续更低的
let maxProfitValue = 0 // 2. 假设初始收益为0,后面每一天的价格减去买入价格就是收益
for (let i = 1; i < prices.length; i++) {
min = Math.min(min, prices[i]) // 3. 变换解决之,使用Math.min对比一下,看那一天的股价最低,就用那个
// 4. 只要收益大的(收益大的记在本子上,收益小的划掉不要)
maxProfitValue = Math.max(maxProfitValue, prices[i] - min) // 5. 已知最低价是min,那么收益就等于卖出价-最低价
}
return maxProfitValue; // 6. 最终得到一个最大收益,并返回
}
Well, seeing this, the force deduction algorithm problem is solved. So the idea is very important: 复杂的问题简单化,在简单化处理的过程中不断寻找规律,从而向复杂化过渡,最终通过寻得的规律解决复杂化的问题
Attachment: Double-layer cyclic violence solution
function maxProfit(prices) {
let arr = [0] // 指定默认收益为0
for (let i = 0; i < prices.length; i++) {
for (let j = i + 1; j < prices.length; j++) {
arr.push(prices[j] - prices[i]) // 把所有计算出的利润都追加到一个数组中
}
}
return Math.max(...arr) // 然后求出这个数组中的最大值即为最大收益
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。