leetcode 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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4] Output: 5 max. difference = 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 In this case, no transaction is done, i.e. max profit = 0.
本质上都是计数器,在某些时候reset计数。
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices: return 0 low = high = prices[0] ans = 0 for i in xrange(1, len(prices)): if prices[i] > high: # 看到高价就贪心 high = prices[i] ans = max(ans, high-low) elif prices[i] < low: low = high = prices[i] # 遇到更低价格就reset return ans
或者是:
int maxProfit(vector<int> &prices) { int maxPro = 0; int minPrice = INT_MAX; for(int i = 0; i < prices.size(); i++){ minPrice = min(minPrice, prices[i]); maxPro = max(maxPro, prices[i] - minPrice); } return maxPro; }
另外的解法:
The logic to solve this problem is same as “max subarray problem” using Kadane's Algorithm
. Since no body has mentioned this so far, I thought it’s a good thing for everybody to know.
All the straight forward solution should work, but if the interviewer twists the question slightly by giving the difference array of prices, Ex: for {1, 7, 4, 11}
, if he gives {0, 6, -3, 7}
, you might end up being confused.
Here, the logic is to calculate the difference (maxCur += prices[i] - prices[i-1]
) of the original array, and find a contiguous subarray giving maximum profit. If the difference falls below 0, reset it to zero.
public int maxProfit(int[] prices) {
int maxCur = 0, maxSoFar = 0;
for(int i = 1; i < prices.length; i++) {
maxCur = Math.max(0, maxCur += prices[i] - prices[i-1]);
maxSoFar = Math.max(maxCur, maxSoFar);
}
return maxSoFar;
}
*maxCur = current maximum value
*maxSoFar = maximum value found so far
举例(遇到拐点):股票价格为【1,3,2,7】,则3-1=2,2-3=-1,-1+2=1(非常巧妙),7-2=5,5+1=6,所以答案是6.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2017-04-06 bleve搜索引擎源码分析之索引——mapping真复杂啊
2017-04-06 我的vim 配置——nerdtree、ack vim、vim sneak