121.卖出股票的最佳时机

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

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

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

思路

  • 简单来说就是,何时买入股票,合适卖出股票
  • 得出利润的最大值
  • 买入要在卖出之前
  • 贪心
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.wereash.scut_hot100.tanxin;

import java.util.Scanner;

/**
* @Author: WereAsh
* @Date:2026-01-29 20:35
**/
public class Solution121 {
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
String[] str=scanner.nextLine().split(",");
int[] prices=new int[str.length];
int n=str.length;
for (int i=0;i<n;i++){
prices[i]=Integer.parseInt(str[i]);
}
int profit=0;
for(int i=0,sell,buy=prices[0];i<n;i++){
buy=Math.min(buy,prices[i]);
sell=prices[i];
profit=Math.max(sell-buy,profit);
}
System.out.println("卖出股票的最大利润为:"+profit);
}
}