当前位置:网站首页>LeetCode热题(12.买卖股票的最佳时机)
LeetCode热题(12.买卖股票的最佳时机)
2022-08-11 03:06:00 【识时务者-HJJ】
12.买卖股票的最佳时机
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
示例 1:
输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
示例 2:
输入:prices = [7,6,4,3,1]
输出:0
解释:在这种情况下, 没有交易完成, 所以最大利润为 0。
提示:
1 <= prices.length <= 105
0 <= prices[i] <= 104
package com.leetcode;
/** * @Author Handsome * @Date 2022/8/10 17:48 * @Version 1.0 */
public class 买卖股票的最佳时机 {
public static void main(String[] args) {
System.out.println(maxProfit1(new int[]{
7, 1, 5, 3, 6, 4}));
System.out.println(maxProfit2(new int[]{
7, 1, 5, 3, 6, 4}));
// 输入 [7,1,5,3,6,4]
// 输出 5
}
/** * 暴力法: * 复杂度分析 * 时间复杂度:O(n^2)。循环运行 n(n−1)/2 次。 * 空间复杂度:O(1)。只使用了常数个变量。 */
public static int maxProfit1(int[] prices) {
int maxprofit = 0;
for (int i = 0; i < prices.length - 1; i++) {
for (int j = i + 1; j < prices.length; j++) {
int profit = prices[j] - prices[i];
if (profit > maxprofit) {
maxprofit = profit;
}
}
}
return maxprofit;
}
/** * 一次遍历: * 复杂度分析 * 时间复杂度:O(n),只需要遍历一次。 * 空间复杂度:O(1),只使用了常数个变量。 */
public static int maxProfit2(int prices[]) {
int minprice = Integer.MAX_VALUE;
int maxprofit = 0;
for (int i = 0; i < prices.length; i++) {
if (prices[i] < minprice) {
minprice = prices[i];
} else if (prices[i] - minprice > maxprofit) {
maxprofit = prices[i] - minprice;
}
}
return maxprofit;
}
}
我的学习论坛
HandsomeForum:用Java编写的学习论坛,打造我们自己的圈子!(http://huangjunjie.vip:66)
边栏推荐
- [机缘参悟-66]:怎样才能让别人愿意帮你:利益共享法则、“大道”、“人性”
- 互换性测量与技术——偏差与公差的计算,公差图的绘制,配合与公差等级的选择方法
- font
- OpenCV founder: Open source must not be completely free!
- 【Unity入门计划】Unity2D动画(1)-动画系统的组成及功能的使用
- google搜索技巧——程序员推荐
- 聊聊对RPC的理解
- 【LeetCode】Day112-repetitive DNA sequence
- Goodbye Chongqing paper invoices!The issuance of electronic invoices for accommodation expenses will soon completely replace the invoices of hotels, catering and gas stations
- 多线程之ThreadPoolExecutor
猜你喜欢
随机推荐
BUU刷题记录
Realization of vending machine function based on FPGA state machine
Ninjutsu_v3_08_2020 - safety penetrating system installation
[BX] and loop
(CVPR-2017)在身体和潜在部位学习深度上下文感知特征以进行行人重识别
增加对 Textbundle 的支持
ES进阶 函数功能语法新特性详解
CSAPP Data Lab
阿里低代码框架 lowcode-engine 之自定义物料篇
Vim and copy and paste from the outside (don't need to install the plugin)
ifconfig与ip命令的比较
Traversal of DOM tree-----modify styles, select elements, create and delete nodes
《人生若如初见》命运多舛,人物饱满,朱亚文角色反差太惊喜
this question in js
ESP32的环境配置(arduino arduino2.0 VScode platform哪个好用?)
Idea (preferred) cherry-pick operation
基于改进YOLOv5轻量化的烟火检测
(Nips-2015)空间变换器网络
怎么删除语句审计日志?
Mysql_Note6









