【Leetcode】Best Time to Buy and Sell Stock

来源:互联网 发布:js 汉字长度 编辑:程序博客网 时间:2024/06/05 11:14

题目链接: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;  }  


1 0