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.
public class Solution { public int maxProfit(int[] prices) { int min = Integer.MAX_VALUE; int max = 0; for (int i = 0; i < prices.length; i++) { min = Math.min(min, prices[i]); max = Math.max(max, prices[i]-min); } return max; } }
相关推荐
同时,我们需要一个变量`buy_price`来存储最近一次买入的价格,如果当前价格低于`buy_price`,我们就更新`buy_price`;如果当前价格高于`buy_price`,我们就计算利润并更新`max_profit`。 ### 算法流程 1. 初始化`...
java java_leetcode题解之Best Time to Buy and Sell Stock with Cooldown
java java_leetcode题解之Best Time to Buy and Sell Stock IV.java
java java_leetcode题解之Best Time to Buy and Sell Stock III.java
java java_leetcode题解之Best Time to Buy and Sell Stock II.java
java java_leetcode题解之Best Time to Buy and Sell Stock I.java
Best Time to Buy and Sell Stock 122 买卖股票的最佳时机 Ⅱ Best Time to Buy and Sell StockⅡ 123 买卖股票的最佳时机 Ⅲ Best Time to Buy and Sell StockⅢ 188 买卖股票的最佳时机Ⅳ Best Time to Buy and ...
121.Best Time to Buy and Sell Stock 122.Best Time to Buy and Sell Stock II 123.Best Time to Buy and Sell Stock III 141.Linked List Cycle 142.Linked List Cycle II 188.Best Time to Buy and Sell Stock IV...
- Best Time to Buy and Sell Stock IV:与前三者不同,可能需要多次买入和卖出。 - Best Time to Buy and Sell Stock with Cooldown:买卖后需要冷却一天。 - Best Time to Buy and Sell Stock with Transaction...
Best Time to Buy and Sell Stock (Easy) 一次交易,找最大收益 for i in prices: low = min(low, i) profit = max(profit, i-low) Best Time to Buy and Sell Stock II (Easy) 可多次交易,找总最大收益 for i in ...
python python_leetcode题解121_Best_Time_to_Buy_and_Sell_Stock
javascript js_leetcode题解之121-best-time-to-buy-and-sell-stock.js
python python_leetcode题解之123_Best_Time_to_Buy_and_Sell_Stock_III
python python_leetcode题解之122_Best_Time_to_Buy_and_Sell_Stock_II
63. 股票的最大利润题目链接Leetcode:121. Best Time to Buy and Sell Stock题目描述可以有一次买入和一次卖出,买入必
javascript js_leetcode题解之123-best-time-to-buy-and-sell-stock-iii.js
javascript js_leetcode题解之122-best-time-to-buy-and-sell-stock-ii.js
第一个问题是“Best Time to Buy and Sell Stock”(121题),题目要求找到一次买入和卖出股票的最好时机,使得收益最大化。解决这个问题的一种有效方法是使用线性扫描,遍历数组找到一个局部最小值作为买入点,再...
7. **122.py** - 可能是LeetCode的122题,"Best Time to Buy and Sell Stock II"(买卖股票的最佳时机II),这是一道关于动态规划或贪心策略的题目,用于找出股票交易的最佳策略。 8. **156.py** - 这可能是...