Skip to content

Commit d670e5e

Browse files
committedApr 23, 2022
feat: add best time to buy and sell stock
1 parent f06874b commit d670e5e

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed
 
Binary file not shown.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
* @Author: Chacha
3+
* @Date: 2022-04-23 23:33:43
4+
* @Last Modified by: Chacha
5+
* @Last Modified time: 2022-04-23 23:59:19
6+
*/
7+
8+
/**
9+
* 来源:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
10+
*
11+
* 给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。
12+
* 在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
13+
* 返回 你能获得的 最大 利润 。
14+
*
15+
* 示例 1:
16+
* 输入:prices = [7,1,5,3,6,4]
17+
* 输出:7
18+
* 解释:在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4 。
19+
* 随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6 - 3 = 3 。
20+
* 总利润为 4 + 3 = 7 。
21+
*
22+
* 示例 2:
23+
* 输入:prices = [1,2,3,4,5]
24+
* 输出:4
25+
* 解释:在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4 。
26+
* 总利润为 4 。
27+
*
28+
* 示例 3:
29+
* 输入:prices = [7,6,4,3,1]
30+
* 输出:0
31+
* 解释:在这种情况下, 交易无法获得正利润,所以不参与交易可以获得最大利润,最大利润为 0 。
32+
*
33+
*
34+
*/
35+
#include <iostream>
36+
#include <vector>
37+
38+
using namespace std;
39+
40+
class Solution
41+
{
42+
private:
43+
/* data */
44+
public:
45+
int maxProfit(vector<int> &prices);
46+
};
47+
48+
/**
49+
* 方法:贪心算法
50+
*
51+
* 思路:
52+
* 本题首先要清楚两点:
53+
* 1.只有一只股票
54+
* 2.当前只有买股票或者买股票的操作
55+
* 想获得利润至少要两天为一个交易单元。
56+
*
57+
* 如果想到其实最终利润是可以分解的,那么本题就很容易了!如何分解呢?
58+
* 假如第0天买入,第3天卖出,那么利润为:prices[3] - prices[0]。
59+
* 相当于(prices[3] - prices[2]) + (prices[2] - prices[1]) + (prices[1] - prices[0])。
60+
* 此时就是把利润分解为每天为单位的维度,而不是从0天到第3天整体去考虑。
61+
* 那么根据prices可以得到每天的利润序列:(prices[i] - prices[i - 1]).....(prices[1] - prices[0])。
62+
*
63+
* 时间复杂度:$O(n)
64+
* 空间复杂度:$O(1)
65+
*
66+
*/
67+
int Solution::maxProfit(vector<int> &prices)
68+
{
69+
int result = 0;
70+
for (int i = 1; i < prices.size(); i++)
71+
{
72+
result += max(prices[i] - prices[i - 1], 0);
73+
}
74+
return result;
75+
};
76+
77+
int main(int argc, char const *argv[])
78+
{
79+
Solution s;
80+
vector<int> prices = {7, 1, 5, 3, 6, 4};
81+
82+
cout << "prices = [7,1,5,3,6,4], 最大利润为" << s.maxProfit(prices) << endl;
83+
84+
return 0;
85+
}

0 commit comments

Comments
 (0)
Failed to load comments.