【LeetCode】Best Time to Buy and Sell Stock 解题报告
来源:互联网 发布:广数g90编程实例 编辑:程序博客网 时间:2024/05/17 19:18
Best Time to Buy and Sell Stock
[LeetCode]
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Total Accepted: 98941 Total Submissions: 274449 Difficulty: Easy
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.
Ways
动态规划求解。
因为买股票再卖掉是要求有先后顺序的。肯定是在前面找到最小值,再找到后面的最大值。不不不,应该说是找到当前项的值与之前最小值的差值的最大值。
动态规划问题,可以用数组去写。我偷看别人的,没用数组。
1.保存在见到这个数值时,之前的所有值的最小值。
2.记录当前值与这个最小值的差。
3.找到在所有里边差值的最大值。
不得不说下面这个方法还是很巧的。因为没有笨的像我一样在每个值时都去遍历查找之前所有值的最小值。而是采用保存下来的方法。
public class Solution { public int maxProfit(int[] prices) { if(prices.length<2) return 0; int maxProfit=0; int min=prices[0]; int cur=0; for(int i=1;i<prices.length;i++){ cur=prices[i]; min=Math.min(min,cur); maxProfit=Math.max(maxProfit,cur-min); } return maxProfit; }}
AC:3ms
Date
2016/5/1 17:59:24
0 0
- LeetCode-Best Time to Buy and Sell Stock-解题报告
- 【LeetCode】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] 121. Best Time to Buy and Sell Stock 解题报告
- [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 解题报告
- Leetcode 121. Best Time to Buy and Sell Stock 股票买卖 解题报告
- Leetcode 122. Best Time to Buy and Sell Stock II 股票买卖2 解题报告
- Leetcode 123. Best Time to Buy and Sell Stock III 股票买卖3 解题报告
- LeetCode解题报告 309. Best Time to Buy and Sell Stock with Cooldown[medium]
- 关于CSS常用用法(持续更新)
- 《移动App测试实战》读书笔记
- CodeForces 329B(BFS)
- 【CodeForces】A. Pouring Rain
- 浅谈UML的概念和模型之UML九种图
- 【LeetCode】Best Time to Buy and Sell Stock 解题报告
- 第一节---简单计算器
- opencv中自定义数据结构读写yml
- solr 集群
- Caffe 体验和学习
- POJ 1003--Hangover
- leetcode——129——Sum Root to Leaf Numbers
- [HDU 5017] Ellipsoid (模拟退火)
- Intent的用法以及原理实现