【LeetCode從零單排】No121 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.
又是時間複雜度,離真相就差一行程式碼。。。還是沒想出來,看了discuss才知道答案。程式碼
public class Solution {
public int maxProfit(int[] prices) {
if (prices.length<=0 || prices.length==1) return 0;
int maxProfit=0;
int minTemp=prices[0];
for(int i=1;i<prices.length;i++){
if(prices[i]<minTemp){
minTemp=prices[i];
}
else{
if(prices[i]-minTemp>maxProfit){
maxProfit=prices[i]-minTemp;
}
}
}
return maxProfit;
}
}
/********************************
* 本文來自部落格 “李博Garvin“
* 轉載請標明出處:http://blog.csdn.net/buptgshengod
******************************************/
相關文章
- [leetcode]Best Time to Buy and Sell StockLeetCode
- [LeetCode] 121. Best Time to Buy and Sell StockLeetCode
- leetcode_best-time-to-buy-and-sell-stock-iiLeetCode
- LeetCode 309. Best Time to Buy and Sell Stock with CooldownLeetCode
- leetcode best-time-to-buy-and-sell-stock-iii(Java)LeetCodeJava
- [LeetCode] 122. Best Time to Buy and Sell Stock IILeetCode
- Best Time to Buy and Sell Stock系列
- 121|Best Time to Buy and Sell Stock
- 121. Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock系列分析
- 貪心法-Best Time to Buy and Sell Stock
- 【Lintcode】393. Best Time to Buy and Sell Stock IV
- 【leetcode】40-best-time-to-buy-and-sell-stock 力扣 121. 買賣股票的最佳時機LeetCode力扣
- 【LeetCode】309. Best Time to Buy and Sell Stock with Cooldown 最佳買賣股票時機含冷凍期(Medium)(JAVA)LeetCodeJava
- 42-best-time-to-buy-and-sell-stock-iii 力扣 123. 買賣股票的最佳時機 III力扣
- 44-best-time-to-buy-and-sell-stock-with-cooldown 力扣 309. 買賣股票的最佳時機包含冷凍期力扣
- [LeetCode] 2073. Time Needed to Buy TicketsLeetCode
- Mysql從零單排-1MySql
- Time Series Analysis (Best MSE Predictor & Best Linear Predictor)
- 從零單排學Redis【黃金】Redis
- 從零單排學Redis【白銀】Redis
- 從零單排學Redis【鉑金一】Redis
- 從零單排學Redis【鉑金二】Redis
- The best LeetCode NodesLeetCode
- SpringBoot從零單排 ------初級入門篇Spring Boot
- 【3y】從零單排學Redis【青銅】Redis
- 「從零單排canal 03」 canal原始碼分析大綱原始碼
- 「從零單排canal 05」 server模組原始碼解析Server原始碼
- 「從零單排canal 07」 parser模組原始碼解析原始碼
- 從零單排,使用 Netty 構建 IM 聊天室~Netty
- 「從零單排canal 06」 instance模組原始碼解析原始碼
- Laravel 從零單排系列教程 01 :Homestead 環境搭建Laravel
- 三分鐘從零單排js靜態檢查JS
- Spring AOP從零單排-織入時期原始碼分析Spring原始碼
- 「從零單排canal 04」 啟動模組deployer原始碼解析原始碼
- 「從零單排HBase 10」HBase叢集多租戶實踐
- [LeetCode] Employee Free TimeLeetCode
- 從零開始單排學設計模式「策略模式」黑鐵 II設計模式
- 從零開始單排學設計模式「UML類圖」定級賽設計模式