动态规划-121. Best Time to Buy and Sell Stock
来源:互联网 发布:手机淘宝保证金怎么交 编辑:程序博客网 时间:2024/06/01 07:18
题目
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: 5max. 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: 0In this case, no transaction is done, i.e. max profit = 0.
题意解读:给定一个数组,数组的第i个元素是第i天的股票价格。如果你只允许进行一次买卖操作(买和买当做一次交易),设计一个算法寻找最大额收益
//d[i]代表[0,i]内交易股票的最大收益 minPrice表示[0,i)之间价格的最小值//状态转移方程 dp[i] = max(dp[i-1],prices[i]-minPrice)class Solution { public int maxProfit(int[] prices) { if(prices == null || prices.length==0) return 0; int[] dp = new int[prices.length]; int minPrice = prices[0]; for(int i = 1; i < prices.length; i++){ minPrice = Math.min(minPrice,prices[i]); dp[i] = Math.max(dp[i-1],prices[i]-minPrice); } return dp[prices.length-1]; }}
阅读全文
0 0
- 动态规划-121. Best Time to Buy and Sell Stock
- 【动态规划】Best Time to Buy and Sell Stock IV
- Best Time to Buy and Sell Stock IV(动态规划)
- 【动态规划】Leetcode编程题解:121. Best Time to Buy and Sell Stock Add to List
- 121.LeetCode Best Time to Buy and Sell Stock(easy)[数组 动态规划]
- 【Leetcode】121. Best Time to Buy and Sell Stock 【动态规划】
- ※ Leetcode - Dynamic Programming - 121. Best Time to Buy and Sell Stock(动态规划)
- 121. Best Time to Buy and Sell Stock 类别:动态规划 难度:easy
- 动态规划——121. Best Time to Buy and Sell Stock[easy]
- 动态规划入门级教学(leetcode)121.Best Time to Buy and Sell Stock
- Leetcode(W8):121. Best Time to Buy and Sell Stock(动态规划)
- Leetcode解题笔记121. Best Time to Buy and Sell Stock [Easy] 动态规划
- LeetCode动态规划思想:Best Time to Buy and Sell Stock III
- LeetCode--Best Time to Buy and Sell Stock (贪心策略 or 动态规划)
- LeetCode--Best Time to Buy and Sell Stock III (动态规划)
- Best Time to Buy and Sell Stock I,II,III 动态规划
- Best Time to Buy and Sell Stock(JAVA)--动态规划
- Best Time to Buy and Sell Stock III(JAVA)-动态规划
- leetcode 354. Russian Doll Envelopes 俄罗斯套娃 + DP动态规划
- 第二章 SQL命令参考-ALTER EXTERNAL TABLE
- jquery简单tab切换 源码
- 查找整数
- 【笔记】计算机科学导论——数据库概论
- 动态规划-121. Best Time to Buy and Sell Stock
- Java中Object类之finalize()方法的详解
- MQTT入门篇
- Rain on your Parade HDU
- 剑指offer之二叉树的深度
- MySql数据库
- 五 . BeautifulSoup库详解及运用
- NET连接MySQL数据库
- lua脚本学习4