因为只能买卖一次,我们把每一天都看一遍,如果在当天卖出的话能获得的最大收益是多少,然后再取最大值,就是答案了。
在某一天卖出的最大收益的条件是:在这一天之前价格最便宜的时候买
c++
class Solution { public: int maxProfit(vector<int>& prices) { int minn = prices[0]; int ans = 0; for(int i = 0 ; i < prices.size() ; i++) { minn = min(minn,prices[i]); ans = max(ans,prices[i]-minn); } return ans; } };
java
import java.util.*; public class Solution { public int maxProfit (int[] prices) { int minn = prices[0]; int ans = 0; for(int i = 0 ; i < prices.length ; i++) { minn = Math.min(minn,prices[i]); ans = Math.max(ans,prices[i]-minn); } return ans; } }
python
class Solution: def maxProfit(self , prices ): # write code here minn = prices[0]; ans = 0; for i in range(0,len(prices)): minn = min(minn,prices[i]); ans = max(ans,prices[i]-minn); return ans;