1. 程式人生 > >【LeetCode-面試演算法經典-Java實現】【121-Best Time to Buy and Sell Stock(最佳買賣股票的時間)】

【LeetCode-面試演算法經典-Java實現】【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.

題目大意

  給一個數組prices[],prices[i]代表股票在第i天的售價,求出只做一次交易(一次買入和賣出)能得到的最大收益。

解題思路

  只需要找出最大的差值即可,即 max(prices[j] – prices[i]) ,i < j。一次遍歷即可,在遍歷的時間用遍歷low記錄 prices[o….i] 中的最小值,就是當前為止的最低售價,時間複雜度為 O(n)。

程式碼實現

演算法實現類

public class Solution {

    public int maxProfit(int[] prices) {

        if (prices == null || prices.length < 1) {
            return 0;
        }

        int
min = prices[0]; int profit = 0; // 第i天的價格可以看作是買入價也可以看作是賣出價 for (int i = 1; i < prices.length; i++) { // 找到更低的買入價 if (min > prices[i]) { // 更新買入價 min = prices[i]; } // 當天的價格不低於買入價 else { // 如果當天買出的價格比之前賣出的價格高
if (profit < prices[i] - min) { // 更新賣出價 profit = prices[i] - min; } } } return profit; } }

評測結果

  點選圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中檢視完整圖片。

這裡寫圖片描述

特別說明