Compare commits
No commits in common. "32033709dcb7ce32adb37a371d7cf33ae865afcb" and "64844c34c7964937f0bdab2f332c745e0ce217b1" have entirely different histories.
32033709dc
...
64844c34c7
2
.gitignore
vendored
2
.gitignore
vendored
@ -25,7 +25,7 @@ pids
|
|||||||
yarn-error.log
|
yarn-error.log
|
||||||
|
|
||||||
# Editor directories and files
|
# Editor directories and files
|
||||||
#.vscode
|
.vscode
|
||||||
.idea
|
.idea
|
||||||
*.suo
|
*.suo
|
||||||
*.ntvs*
|
*.ntvs*
|
||||||
|
8
.vscode/settings.json
vendored
8
.vscode/settings.json
vendored
@ -1,8 +0,0 @@
|
|||||||
{
|
|
||||||
"C_Cpp.clang_format_fallbackStyle": "LLVM",
|
|
||||||
"editor.codeActionsOnSave": {
|
|
||||||
"source.fixAll.eslint": "always"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
@ -1,37 +0,0 @@
|
|||||||
/*
|
|
||||||
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
|
|
||||||
|
|
||||||
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
|
|
||||||
|
|
||||||
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
|
|
||||||
|
|
||||||
示例 1:
|
|
||||||
|
|
||||||
输入:[7,1,5,3,6,4]
|
|
||||||
输出:5
|
|
||||||
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
|
|
||||||
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {number[]} prices
|
|
||||||
* @return {number}
|
|
||||||
* 思路:先设置一个变量minPrice 用于保存数组中最小的价格,初始值为无穷大,依次遍历数组,如果有元素比他小那么就
|
|
||||||
* 替换为当前元素,如果遍历的元素比他还大那就说明在“这一天”是可以卖掉的,但是利润不一定是最大的,多以我们还需要
|
|
||||||
* 一个全局变量 maxProfit来表示例如,初始值为0,如果这一天卖掉的利润比之前的最大利润大,就可以替换为当前利润,
|
|
||||||
* 最后返回当前利润
|
|
||||||
*/
|
|
||||||
function calculateProfit(prices) {
|
|
||||||
let minPrice = Infinity;
|
|
||||||
let maxProfit = 0;
|
|
||||||
for (const price of prices) {
|
|
||||||
if (price < minPrice) {
|
|
||||||
minPrice = price;
|
|
||||||
} else if (price - minPrice > maxProfit) {
|
|
||||||
maxProfit = price - minPrice;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return maxProfit;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(calculateProfit([5, 2, 1, 34, 55]));
|
|
Loading…
x
Reference in New Issue
Block a user