买卖股票的最好时机
2023/2/11小于 1 分钟
买卖股票的最好时机
题目链接
题目描述
刷题思路
代码实现
/*
* @Description: 买卖股票的最好时机
* @Version: Beta1.0
* @Author: 微信公众号:储凡
* @Date: 2021-04-29 23:27:18
* @LastEditors: 微信公众号:储凡
* @LastEditTime: 2021-05-03 15:00:53
*/
/**
* 暴力
*/
export function maxProfit(prices) {
// 最低点买入,最高点卖出,收益最大 实际求的是一个子序列,最大和最小的差值 最小在前,最大在后
// 最大收益为0 其他都不算收益
let max = 0
for (let index = 0; index < prices.length; index++) {
const start = prices[index]
const end = Math.max(...prices.slice(index + 1))
if (end - start > max) {
max = end - start
}
}
return max
}
/**
* 处理买点,卖点
*/
export function maxProfitCount(prices) {
// 最大收益为0 其他都不算收益
let max = 0
// 定义最小的值为买入
let minPrice = Infinity
for (let index = 0; index < prices.length; index++) {
const start = prices[index]
// 处理买点
if (start < minPrice) {
minPrice = start
}
// 处理卖点,获取最大收益
if (start - minPrice > max) {
max = start - minPrice
}
}
return max
}一些建议
更新日志
2024/7/29 23:43
查看所有更新日志
5a2b2-于c0f2d-于06596-于9b9e4-于b0275-于5f1e1-于02ab1-于8de1a-于d0347-于74e84-于ced18-于a23ce-于e34c0-于74aa9-于3c22c-于9bbe9-于e4c74-于
