栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 股票最佳交易时机 LeetCode力扣 复杂度为O(n) 笔试、面试高频

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 股票最佳交易时机 LeetCode力扣 复杂度为O(n) 笔试、面试高频

话不多说,直接上代码。
import java.util.Scanner;

public class Main{

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int array[] = new int[5];
		Scanner in = new Scanner(System.in);
		for(int i = 0; i < 5; i++) {
			array[i] = in.nextInt(); 
		}
		int gap = maxProfit(array);
		System.out.print(gap);
		
	}
	
	// 股票交易最佳时机,采用一次遍历
	// 思路:假设你从一周中选择最低价格那天买入,当天卖出,那么在最低点买入,最高点卖出
	public static int maxProfit(int[] prices) {
		
		int maxProfit = 0; // 最大收益
        int buy = Integer.MAX_VALUE; // 当天购买的价格
        for(int i = 0; i < prices.length; i++){
            if(prices[i] < buy){
                buy = prices[i];
            }else if(prices[i] - buy > maxProfit){
                maxProfit = prices[i] - buy;
            }
        }
        return maxProfit;
    }

}
测试结果,上图:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/762715.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号