LeetCode——Best Time to Buy and Sell Stock

來源:互聯網
上載者:User

標籤:leetcode

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.

原題連結:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/

題目:假設你有一個數組,其中的第 i 個元素代表給定的第 i 天的股票價格。

如果你被允許至多完成一個交易(如,買一和賣一股票),設計一個演算法找出最大的利潤。

最Naive的解法,就是遍曆所有的  後 - 前 ,找出最小值。逾時了。

public static int maxProfit(int[] prices){int len = prices.length;if(len <= 1)return 0;int max = 0;for(int i=0;i<len;i++){for(int j=i+1;j<len;j++){int profit = prices[j] - prices[i];if(max < profit)max = profit;}}return max;}

下面的方法就簡便多了,首先賦首元素的值給最小,依次向後計算利潤,每次與最大值比較並儲存新的最大值和新的最小值。

public static int maxProfit(int[] prices){int len = prices.length;if(len <= 1)return 0;int min = prices[0],max = 0;for(int i=1;i<len;i++){int profit = prices[i] - min;if(max < profit)max = profit;if(min > prices[i])min = prices[i];}return max;} 


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.