[leetcode]解题报告121. Best Time to Buy and Sell Stock
来源:互联网 发布:dnf进决斗场网络中断 编辑:程序博客网 时间:2024/05/22 02:21
这题,似曾相识。。。记得今年春招的时候,在今日头条网络笔试安卓的时候出现过。。。。
个人想法:—面试算法里也讲过这种问题——最大子列和问题。。。
1.选择数据结构
既然是best time,肯定找一个低价、时间买入,高价、时间卖出。我觉得适合map存储。
2.嗯。。。果断gg啊,本来就想复杂了。
别人的想法
public class Solution { 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 maxCur; }}
果然很简单。。。一个max,保存当前一段数组的和,如果这个和比之前的和大,那么他就是最后答案。。。
总结:
果然很简单。。。当时很傻没想出来,现在很傻也没想出来。。。果然需要多做一做
为什么不需要map?因为输入的数组已经蕴含时间顺序,所以map个鸡毛
下面的代码,核心在maxCur += prices[i]-prices[i-1]。果然是特别简单。
希望傻这一次就够了
阅读全文
0 0
- LeetCode-Best Time to Buy and Sell Stock-解题报告
- 【LeetCode】Best Time to Buy and Sell Stock 解题报告
- [leetcode] 121. Best Time to Buy and Sell Stock 解题报告
- Leetcode 121. Best Time to Buy and Sell Stock 股票买卖 解题报告
- [Leetcode] 121. Best Time to Buy and Sell Stock 解题报告
- [leetcode]解题报告121. Best Time to Buy and Sell Stock
- 【LeetCode】121.Best Time to Buy and Sell Stock解题报告
- 【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告
- LeetCode-Best Time to Buy and Sell Stock II-解题报告
- LeetCode-Best Time to Buy and Sell Stock III -解题报告
- LeetCode-Best Time to Buy and Sell Stock IV -解题报告
- 【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告
- [leetcode] 123. Best Time to Buy and Sell Stock III 解题报告
- [leetcode] 122. Best Time to Buy and Sell Stock II 解题报告
- [leetcode] 309. Best Time to Buy and Sell Stock with Cooldown 解题报告
- [leetcode] 188. Best Time to Buy and Sell Stock IV 解题报告
- leetcode 309. Best Time to Buy and Sell Stock with Cooldown 解题报告
- LeetCode 122. Best Time to Buy and Sell Stock II 解题报告
- Win7屏幕刷新率怎么设置?
- wget失败原因及解决方案
- 有关Rxjava和retrofit
- 集成Kotlin到Android
- Android6.0 UnsatisfiedLinkError couldn't find "xxx.so"
- [leetcode]解题报告121. Best Time to Buy and Sell Stock
- Ubuntu 16.04+ROS kinetic+rviz模拟turtlebot机器人时出现的问题-
- 一次完整的HTTP请求与响应涉及了哪些知识
- JAVA设计模式二简单工厂模式
- js字符串截取函数slice()、substring()、substr()以及split()、John() 、indexOf()的用法
- git遇到的问题之“Please make sure you have the correct access rights and the repository exists.”
- iOS代码实现两张图片合成一个
- JavaScript版几种常见排序算法
- TCP端口