算法:买卖股票的最佳时机
算法 大约 974 字题目
给定一个数组prices
,它的第i
个元素prices[i]
表示一支给定股票第i
天的价格。
你只能选择某一买入这只股票,并选择在未来的某一个不同的日子卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回0
。
实现
方法一
- 记录【今天之前买入的最小值】
- 计算【今天之前最小值买入,今天卖出的获利】,也即【今天卖出的最大获利】
- 比较【每天的最大获利】,取最大值即可
public static int maxProfit(int[] prices) {
int min = prices[0];
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
int profit = prices[i] - min;
maxProfit = Math.max(profit, maxProfit);
min = Math.min(min, prices[i]);
}
return maxProfit;
}
方法二
暴力比较
public static int maxProfit(int[] prices) {
int maxProfit = 0;
for (int i = 0; i < prices.length - 1; i++) {
for (int j = i + 1; j < prices.length; j++) {
if (prices[j] > prices[i]) {
maxProfit = Math.max(maxProfit, prices[j] - prices[i]);
}
}
}
return maxProfit;
}
超出时间限制。- -!
LeetCode 原题地址
https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/comments
阅读 1509 · 发布于 2021-02-25
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Vue slot 插槽阅读 427
-
Maven Fatal error compiling: 错误: 无效的目标发行版:17 -> [Help 1]阅读 2795
-
软考-系统架构设计师:性能评价方法阅读 3283
-
Notepad++ 保存 Ctrl-S 显示 DC3 ,搜索 Ctrl-F 显示 ACK 解决办法阅读 7276
-
PHP 获取毫秒值时间戳阅读 3361
-
Java G1 垃圾收集器开启字符串去重阅读 1986
-
IDEA 新主题 UI阅读 234
-
Vue2 指令阅读 495
-
Linux 命令行快捷键 Ctrl+R 搜索上一个命令和下一个命令阅读 269
-
macOS Rust Cargo 添加镜像阅读 326