121. Best Time to Buy and Sell Stock
来源:互联网 发布:网络自制访谈节目 编辑:程序博客网 时间:2024/06/16 17:41
一、题目概述
给定一个数组,其中第i个元素代表第i天股票的价格。
如果你最多被允许完成一次交易(即,购买并抛售一份股票),设计一种算法寻找最大利润。
- 示例1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
最大差值为6-1=5,(而非7-1=6,因为卖出价格需要高于买入价格) - 示例2:
Input: [7, 6, 4, 3, 1]
Output: 0 此种情况下,不进行交易,利润最大为0。
函数原型: int maxProfit(vector<int>& prices)
二、编程思路
求
即求
令
即是最长连续子序列问题。
最长子序列
对于序列diff,令dp[i]表示diff[i]结尾的最长子序列之和,则有如下状态转移方程:
三、程序设计
class Solution {public: int maxProfit(vector<int>& prices) { if(prices.size()<2) return 0; vector<int> diff; for(int i=1;i<prices.size();i++){ diff.push_back(prices[i]-prices[i-1]); } int max=0,global_max=0; for(int i=0;i<diff.size();i++){ max+=diff[i]; if(max>global_max) global_max=max; if(max<0) max=0; } return global_max; }};
四、实验心得
可以对问题进行适当转化,使其变为经典问题进行解决。
0 0
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time To Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- 欢迎使用CSDN-markdown编辑器
- android开发-后台邮件统计异常的需求
- @Override must override a superclass method 问题解决
- 字段 bit 、tinyint(1) 使用 boolean 类型映射解决方法
- git操作
- 121. Best Time to Buy and Sell Stock
- Lintcode 二进制中有多少个1
- 测试一下
- 安卓,Logger,日志管理
- 关于c语言几种排序方法的理解
- dubbo应用中的一些问题
- css兼容处理
- redis在直接保存序列化对象字节码时的问题
- spring session共享