LeetCode 122. Best Time to Buy and Sell Stock II
来源:互联网 发布:linux查看声卡驱动 编辑:程序博客网 时间:2024/06/05 05:11
Description
Say you have an array for which the
ith element is the price of a given stock on dayi .
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).
Solution
由于题意设置可以无限次买入和卖出股票,所以只需从第二天开始,如果当前价格比之前价格高,则把差值加入利润中,即昨天买入,今日卖出,若明日价更高的话,还可以今日买入,明日再卖出。以此类推,遍历完整个数组后即可求得最大利润。
class Solution {public: int maxProfit(vector<int>& prices) { int res = 0, n = prices.size(); for (int i = 0; i < n - 1; ++i) { if (prices[i] < prices[i + 1]) { res += prices[i + 1] - prices[i]; } } return res; }};
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】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
- 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
- bzoj 3230 相似子串
- python sqlalchemy core
- Perl学习笔记整理
- android分辨率 尺寸 dpi换算
- 循环链表之双循环链表
- LeetCode 122. Best Time to Buy and Sell Stock II
- 在linux下用C写一个HelloWorld(GCC版)
- zoc for mac序列号
- ROC vs PRC
- quartz 学习笔记 1
- 理解 指针数组 数组指针 函数指针 函数指针数组 指向函数指针数组的指针
- P1181 数列分段Section I
- springMVC底层源码设计思想
- 竟然是老用户了