LeetCode 122 Best Time to Buy and Sell Stock II
来源:互联网 发布:session php注册示例 编辑:程序博客网 时间:2024/06/05 02:55
题目:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
题目链接题意:
给一个数组prices,其中的每一个元素代表一天股票的价格,买与卖都是这个价,第i个元素代表第i天的价格,问经过一定规划后,可是收益最大,最大利益是多少?
要求:
- 在一天之内只允许单个操作。
- 只允许单买和单卖,当手里有股票未卖掉,不许买新的股票。
分析:
对于给定的一个数组而言,每天价格是多少是已知的,同时,收益等于卖出的价格减去买入的价格,所以可以通过分析数据得出:
- 当 prices[i] <= prices[i + 1] 时,可以选择观望,等待至第 i + 1 天。
- 当 prices[i] > prices[i + 1] 时,选择卖出股票。
这个问题也就变成了上升子序列的变形题目。求出每个上升子序列的首位之差,并进行求和。
代码如下:
class Solution {public: int maxProfit(vector<int>& prices) { int ans = 0; for (int i = 0; i + 1 < prices.size(); i++) { if (prices[i] < prices[i + 1]) { ans -= prices[i]; while (i+1 < prices.size() && prices[i+1] > prices[i]) i++; ans += prices[i]; } } return ans; }};
阅读全文
0 0
- LeetCode 122: Best Time to Buy and Sell Stock II
- LeetCode 122 Best Time to Buy and Sell Stock II
- LeetCode 122 Best Time to Buy and Sell Stock II
- LeetCode: Best Time to Buy and Sell Stock II [122]
- [leetcode 122] Best Time to Buy and Sell Stock II
- leetcode-122 Best Time to Buy and Sell Stock II
- leetcode || 122、Best Time to Buy and Sell Stock II
- LeetCode 122: Best Time to Buy and Sell Stock II
- Leetcode# 122 Best Time to Buy and Sell Stock II
- leetcode 122: Best Time to Buy and Sell Stock II
- leetCode #122 Best Time to Buy and Sell Stock II
- leetcode: (122) Best Time to Buy and Sell Stock II
- 122 Best Time to Buy and Sell Stock II [Leetcode]
- LeetCode 122: Best Time to Buy and Sell Stock II
- LeetCode 122 Best Time to Buy and Sell Stock II
- 【LEETCODE】122-Best Time to Buy and Sell Stock II
- [leetcode 122] Best Time to Buy and Sell Stock II
- 【leetcode】【122】Best Time to Buy and Sell Stock II
- 程序员写的脚本
- 二叉查找树、平衡二叉树、红黑树、B-/B+树性能对比
- comm命令
- 基于Nsight Eclipse Edition的高斯滤波的实现(二)
- 循环
- LeetCode 122 Best Time to Buy and Sell Stock II
- 【数据结构】求二叉树中两个结点最近的公共祖先
- 抽象类、接口和内部类
- Matplotlib.pyplot 常用方法(二)
- 一条用来表示“思路非常乱。。。”的博客
- 等精度测频的原理和基于FPGA的实现
- 哈密顿绕行世界问题 HDU
- qduoj 65 again and again 字典树
- Memcached基本操作