question:
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.
class Solution { public: int maxProfit(vector<int> &prices) { int n = prices.size(); if(n <= 1) return 0; int maxAll = 0; int maxLast = 0; int maxJump = 0; int mjb = prices[0]; // max jump begin element vector<int>::iterator it = prices.begin(); vector<int>::iterator li = it; it++; for(;it != prices.end(); it++, li++) { if(*it >= *li) { maxLast += *it - *li; maxJump += *it - *li; } else { maxLast = 0; if(*it < mjb) { mjb = *it; maxJump = 0; } else { maxJump += *it - *li; } } maxAll = max(maxAll, maxLast); maxAll = max(maxAll, maxJump); } return maxAll; } };
相关推荐
java java_leetcode题解之Best Time to Buy and Sell Stock I.java
- 如果当前价格`prices[i]`小于`buy_price`,则更新`buy_price`为`prices[i]`。 - 否则,计算`profit = prices[i] - buy_price`,并将`max_profit`更新为`max(max_profit, profit)`。 3. 返回`max_profit`作为最终...
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
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 ...
python python_leetcode题解121_Best_Time_to_Buy_and_Sell_Stock
javascript js_leetcode题解之121-best-time-to-buy-and-sell-stock.js
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...
python python_leetcode题解之123_Best_Time_to_Buy_and_Sell_Stock_III
python python_leetcode题解之122_Best_Time_to_Buy_and_Sell_Stock_II
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 IV:与前三者不同,可能需要多次买入和卖出。 - Best Time to Buy and Sell Stock with Cooldown:买卖后需要冷却一天。 - Best Time to Buy and Sell Stock with Transaction...
股票收益leetcode LeetCode 股票问题 Best Time to Buy and Sell Stock ...一次交易,找最大收益 ...i ...i) ...i-low) ...i-buy1) #找第一次交易最大收益 buy2 = min(buy2, i-prof1) #找用第一次收益购买的股票仍
63. 股票的最大利润题目链接Leetcode:121. Best Time to Buy and Sell Stock题目描述可以有一次买入和一次卖出,买入必
leetcode 分类 LeetCode LeetCode Java Solution 2018年5月31日 更新 最近刷了一遍 ...题,把相似的题目都放在了一起,比如Best Time to Buy and Sell Stock的6道题,这些题目放在一起刷效果更好。 简书博客:
Best Time to Buy and Sell Stock II #136 Single Number #150 Evaluate Reverse Polish Notation #169 Majority Element #171 Excel Sheet Column Number #217 Contains Duplicate #226 Invert Binary Tree #237 ...