首页 > 其他分享 >【LeeCode】121. 买卖股票的最佳时机

【LeeCode】121. 买卖股票的最佳时机

时间:2022-12-20 23:32:31浏览次数:81  
标签:int max len util 121 LeeCode 最佳时机 prices public

【题目描述】

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果不能获取任何利润,返回 0 

​https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/?favorite=2cktkvj​

【示例】

【LeeCode】121. 买卖股票的最佳时机_i++

【代码】​​天方​

import java.util.*;
import java.util.stream.Collectors;
// 2022-12-20

class Solution {
public int maxProfit(int[] prices) {
// 假设第一个元素是最小值
int min = prices[0];
int max = 0;
int len = prices.length;
if (len < 2) return max;

for (int i = 1; i < len; i++){
// 持续迭代获取最小的值 这样就能保证最小的值是在后面的
if (prices[i] < min) min = prices[i];

if (prices[i] - min > max) {
max = prices[i] - min;
}
}
System.out.println(max);
return max;
}

}
public class Main{
public static void main(String[] args) {
int[] arr = {7,1,5,3,6,4};
new Solution().maxProfit(arr); // 输出: 5
}
}

【代码】​​DUNCAN​

import java.util.*;
import java.util.stream.Collectors;
// 2022-12-20

class Solution {
public int maxProfit(int[] prices) {
// 假设第一个元素是最小值
int len = prices.length;
int res = 0;
// 前一天卖出可以获取的最大利润
int pre = 0;
// 7,1,5,3,6,4
for (int i = 1; i < len ; i++) {
// 获取利润差
int diff = prices[i] - prices[i - 1];
// 最大的利润 = 第i-1天卖出的利润 + 利润差
pre = Math.max(pre + diff, 0); // 利润最少也是0
res = Math.max(res, pre);
}
return res;
}

}
public class Main{
public static void main(String[] args) {
int[] arr = {7,1,5,3,6,4};
new Solution().maxProfit(arr); // 输出: 5
}
}

【代码】admin

暴力PO解, 超时了,200/211的通过率

import java.util.*;
import java.util.stream.Collectors;
// 2022-12-19

class Solution {
public int maxProfit(int[] prices) {
int max = 0;
int len = prices.length;
if (len < 2) return max;
for (int i = 0; i < len; i++){
for (int j = i + 1; j < len; j++) {
if (prices[i] < prices[j]){
int tmp = prices[j] - prices[i];
max = Math.max(tmp, max);
}
}
}
System.out.println(max);

return max;
}

}
public class Main{
public static void main(String[] args) {
int[] arr = {7,1,5,3,6,4};
new Solution().maxProfit(arr); // 输出: 5
}
}


标签:int,max,len,util,121,LeeCode,最佳时机,prices,public
From: https://blog.51cto.com/u_13682316/5957021

相关文章