中山大学算法课程题目详解(第九周)
来源:互联网 发布:胡克霍根身体数据 编辑:程序博客网 时间:2024/06/05 20:46
问题描述:
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天的股市价格减去[0,i-1]天内的最小股市价格,当第i天的股市价格比漆面最低股市价格还低,则更新最低股市价格。然后取最大的股市收益,为DP问题。用profit[i]表示第i天的收益,则minBuyPrice = min(minBuyPrice, prices[i]),并且profit[i] = prices[i]-minBuyPrice. 然后取profit中的最大值。
代码实现:
int maxProfit(vector<int>& prices) {if (prices.size() == 0) {return 0;}int maxprofit = 0;int minPrice = prices[0];for (int i = 1; i < prices.size(); i++) {minPrice = min(minPrice, prices[i]);if (maxprofit < (prices[i] - minPrice)) {maxprofit = prices[i] - minPrice;}}return maxprofit;}
阅读全文
0 0
- 中山大学算法课程题目详解(第九周)
- 中山大学算法课程题目详解(第二周)
- 中山大学算法课程题目详解(第三周)
- 中山大学算法课程题目详解(第五周)
- 中山大学算法课程题目详解(第六周)
- 中山大学算法课程题目详解(第七周)
- 中山大学算法课程题目详解(第八周)
- 中山大学算法课程题目详解(第十周)
- 中山大学算法课程题目详解(第十二周)
- 中山大学算法课程题目详解(第一周)
- 中山大学算法课程题目详解(第四周)
- 中山大学算法课程题目详解(第十一周)
- Leetcode算法课程第九周(补)
- 中山大学软件学院的课程
- 中山大学软件学院的课程
- 算法分析与设计课程作业第九周#1#2#3
- 第九周剩余的题目
- Boolan* C++课程第九周笔记
- 19、TensorFlow 实现最近邻分类器(K=1)
- 过滤掉字符串中的非数字
- Leetcode350 Intersection of Two Arrays II &Leetcode Intersection of Two Arrays
- C语言面向对象编程之二:继承
- 20、TensorFlow 中 MNIST 数据集的使用
- 中山大学算法课程题目详解(第九周)
- TextView 跑马灯
- 自定义类型与内存对齐
- 一文读懂卷积神经网络
- JavaScript实现排序和搜索
- dubbo hello world
- #448 div2 a Pizza Separation
- C语言面向对象编程之三:虚函数与多态
- HLS 协议