leetCode 121Best Time to Buy and Sell Stock

it2022-05-05  191

leetCode 121 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.

题解:

这道题只让做一次transaction,那么就需要找到价格最低的时候买,价格最高的时候卖(买价的日期早于卖价的日期)。从而转化为在最便宜的时候买入,卖价与买价最高的卖出价最大时,就是我们要得到的结果。

因为我们需要买价日期早于卖价日期,所以不用担心后面有一天价格特别低,而之前有一天价格特别高而错过了(这样操作是错误的)。

所以,只许一次遍历数组,维护一个最小买价,和一个最大利润(保证了买在卖前面)即可。

1 public class Solution{ 2 public int maxProfit(int[] prices){ 3 if(prices.length <= 1 || prices ==null){ 4 return 0; 5 } 6 7 int max = 0; 8 int lowest = prices[0]; 9 10 for(int i = 0; i < prices.length; i++){ 11 if(prices[i] < lowest){ 12 lowest = prices[i]; 13 } 14 if(prices[i]-lowest > max){ 15 max = prices-lowest; 16 } 17 18 return max; 19 } 20 }

 参考:http://www.cnblogs.com/springfor/p/3877059.html

转载于:https://www.cnblogs.com/hewx/p/4532532.html


最新回复(0)