LeetcodeBest Time to Buy and Sell Stock
Posted wuezs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetcodeBest Time to Buy and Sell Stock相关的知识,希望对你有一定的参考价值。
题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
题目:
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
思路:
当前元素的最大收益只跟前面最小元素有关。
算法:
public int maxProfit(int[] prices) { int maxProfit = 0; int minEle = Integer.MAX_VALUE; for (int i = 0; i < prices.length; i++) { maxProfit = Math.max(maxProfit, prices[i]-minEle); minEle = Math.min(minEle, prices[i]); } return maxProfit; }
以上是关于LeetcodeBest Time to Buy and Sell Stock的主要内容,如果未能解决你的问题,请参考以下文章
Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock II
最强解析面试题:best-time-to-buy-and-sell-stock
最强解析面试题:best-time-to-buy-and-sell-stock
121. Best Time to Buy and Sell Stock