LeetCode#121. Best Time to Buy and Sell Stock
来源:互联网 发布:sql with用法 编辑:程序博客网 时间:2024/06/17 20:21
- 题目:一个数组,求数组中两个元素的最大差(这两个元素必须小的在前,大的在后)
- 难度:Easy
- 思路:类似求最大子序列和,用动态规划来做,遍历一次数组,用currMin记录当前元素之前的数组最小值,如果当前元素大于currMin,则取max和nums[i]-currMin两者中的较大者。每一次遍历都更新currMin
- 代码:
方法一:
public class Solution { public int maxProfit(int[] prices) { if(prices == null || prices.length == 0 || prices.length == 1){ return 0; } int max = 0; int currMin = prices[0]; for(int i = 1; i < prices.length; i++){ if(prices[i] > currMin){ max = Math.max(max, prices[i]-currMin); } currMin = Math.min(currMin, prices[i]); } return max; }}
方法二:
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; }
阅读全文
0 0
- 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
- 121. Best Time to Buy and Sell Stock LeetCode
- [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 *** 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
- 121.[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
- makefile 工具基本使用(2)
- 顺序表的操作
- CNN(卷积神经网络)
- 戒色
- 非极大值抑制(Non-maximum suppression, NMS)
- LeetCode#121. Best Time to Buy and Sell Stock
- 打印对象和toString方法
- 帅哥陈爬虫笔记ppppython(1),我也不知道起个什么题目
- 网络通讯的封包和拆包
- easyui textarea 赋值和获取值
- Nginx+FastDFS
- qt程序打包
- Hadoop日记——Hadoop2.x介绍
- 分布式缓存技术redis学习系列(五)——spring-data-redis与JedisPool的区别、使用ShardedJedisPool与spring集成的实现及一致性哈希分析