Leetcode|Leetcode 121. Best Time to Buy and Sell Stock
【Leetcode|Leetcode 121. Best Time to Buy and Sell Stock】文章作者:Tyan
博客:noahsnail.com|CSDN|
1. Description
文章图片
Best Time to Buy and Sell Stock 2. Solution
- Version 1
class Solution {
public:
int maxProfit(vector& prices) {
int max_profit = 0;
for(int i = 0;
i < prices.size();
i++) {
for(int j = i + 1;
j < prices.size();
j++) {
int profit = prices[j] - prices[i];
if(profit > max_profit) {
max_profit = profit;
}
}
}
return max_profit;
}
};
- Version 2
class Solution {
public:
int maxProfit(vector& prices) {
int max = 0;
int min = INT_MAX;
vector current_max(prices.size());
vector current_min(prices.size());
int max_profit = 0;
int size = prices.size();
for(int i = 0;
i < size;
i++) {
if(prices[i] < min) {
min = prices[i];
}
current_min[i] = min;
}
for(int i = size - 1;
i >= 0;
i--) {
if(prices[i] > max) {
max = prices[i];
}
current_max[i] = max;
}
for(int i = 0;
i < size;
i++) {
int profit = current_max[i] - current_min[i];
if(profit > max_profit) {
max_profit = profit;
}
}
return max_profit;
}
};
- Version 3
class Solution {
public:
int maxProfit(vector& prices) {
int min = INT_MAX;
int max_profit = 0;
for(int i = 0;
i < prices.size();
i++) {
if(prices[i] < min) {
min = prices[i];
}
else if(prices[i] - min > max_profit) {
max_profit = prices[i] - min;
}
}
return max_profit;
}
};
Reference
- https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
推荐阅读
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- leetcode|leetcode 92. 反转链表 II
- 二叉树路径节点关键值和等于目标值(LeetCode--112&LeetCode--113)
- LeetCode算法题-11.|LeetCode算法题-11. 盛最多水的容器(Swift)
- LeetCode(03)Longest|LeetCode(03)Longest Substring Without Repeating Characters
- Leetcode|Leetcode No.198打家劫舍
- [leetcode数组系列]1两数之和
- 数据结构和算法|LeetCode 的正确使用方式
- leetcode|今天开始记录自己的力扣之路
- LeetCode|LeetCode 876. 链表的中间结点