java 买卖股票的最佳时机只做一笔交易

本文介绍了一种用于确定股票买卖最佳时机的算法,通过寻找价格序列中的最低点和最高点之间的最大差值来计算可能的最大利润。算法遍历一次价格序列,记录下遇到的最低价格和基于该价格能获得的最大利润。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


public class Stock1
{
    public static int maxProfit(int prices[])
    {
        int min =  Integer.MAX_VALUE;  // 最小的谷值
        int val = 0;    //最大的利润
        for (int i = 0; i < prices.length; i++)
        {
            // 比最小值小
            if (prices[i] < min )
            {
                min = prices[i];// 把当前最小值赋值
            } 
            // 比最小值大
            else if (prices[i] - min > val )
            {

                val = prices[i] - min ;// 当前比最小值大,得出差值如果大于最大获利,就复制
            }
        }
        return val ;
    }

    
    public static void main(String[] args)
    {
        int[] prices =    { 7, 1, 5, 3, 6, 4 };
        int[] prices1 =    { 1, 2, 3, 4, 5 };
        int[] prices2 =    { 7, 6, 4, 3, 1 };
        int[] prices3 =    { 7, 6, 8, 3, 5, 6, 1 };
        // System.out.println(maxProfit2(prices));
        // System.out.println(maxProfit2(prices1));
        // System.out.println(maxProfit2(prices2));
        System.out.println(maxProfit(prices3));
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值