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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
買一個股票and 買一個股票,設計一個演算法找到最大的利潤
Note that you cannot sell a stock before you buy one.
Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
class Solution {
public int maxProfit(int[] prices) {
int max_profit=0;
int min_value=Integer.MAX_VALUE;
int profit=0;
for(int i=0;i<prices.length;i++){
if(prices[i]<min_value){
min_value=prices[i];
}else if(prices[i]-min_value>max_profit){
max_profit=prices[i]-min_value;
}
}
return max_profit;
}
}
相關文章
- 121. Best Time to Buy and Sell Stock
- [LeetCode] 121. Best Time to Buy and Sell StockLeetCode
- [leetcode]Best Time to Buy and Sell StockLeetCode
- Best Time to Buy and Sell Stock系列
- Best Time to Buy and Sell Stock系列分析
- 貪心法-Best Time to Buy and Sell Stock
- leetcode_best-time-to-buy-and-sell-stock-iiLeetCode
- [LeetCode] 122. Best Time to Buy and Sell Stock IILeetCode
- leetcode best-time-to-buy-and-sell-stock-iii(Java)LeetCodeJava
- 【Lintcode】393. Best Time to Buy and Sell Stock IV
- LeetCode 309. Best Time to Buy and Sell Stock with CooldownLeetCode
- 【leetcode】40-best-time-to-buy-and-sell-stock 力扣 121. 買賣股票的最佳時機LeetCode力扣
- 42-best-time-to-buy-and-sell-stock-iii 力扣 123. 買賣股票的最佳時機 III力扣
- 【LeetCode】309. Best Time to Buy and Sell Stock with Cooldown 最佳買賣股票時機含冷凍期(Medium)(JAVA)LeetCodeJava
- 44-best-time-to-buy-and-sell-stock-with-cooldown 力扣 309. 買賣股票的最佳時機包含冷凍期力扣
- Time Series Analysis (Best MSE Predictor & Best Linear Predictor)
- [LeetCode] 2073. Time Needed to Buy TicketsLeetCode
- 【PAT_1062】To Buy or Not to Buy
- 121
- TTEC遭勒索軟體攻擊後影響客戶業務 包括Verizon、Best Buy、美國銀行等
- SAP Stock Inconsistency
- The best LeetCode NodesLeetCode
- Best Team With No Conflicts
- B. Rudolf and 121
- SELL 指令碼程式設計指令碼程式設計
- Best Wishes「兔」You!
- 121、秦中寄遠上人
- 題解:P10688 Buy Tickets
- 攻防世界-best_rsa
- 25 Best Java Books In 2022Java
- 我的收藏週刊121
- BUUCTF-Misc(121-130)
- time time_t tm用法
- How to Buy a Fake Cal Poly Pomona Diploma Quickly?UI
- 矩陣樹定理 BEST 定理矩陣
- [ARC060F] Best Representation
- The Best Way to Export an SVG from SketchExportSVG
- AtCoder Regular Contest 121 D - 1 or 2