本文主要是介绍leetcode121~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 class BestTimetoBuyandSellStock {public int maxProfit(int[] prices) {if(prices==null || prices.length==0) {return 0;}//记录最低点int min = Integer.MAX_VALUE;int profit = 0;for(int i: prices) {min = i<min ? i:min;profit = (i-min)>profit ?i-min:profit;}return profit;}
}
这篇关于leetcode121~Best Time to Buy and Sell Stock的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!