【leedcode】121. Best Time to Buy and Sell Stock
来源:互联网 发布:数据库第三版课后答案 编辑:程序博客网 时间:2024/05/21 11:05
题目:
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.、
分析:相较于同系列题目的II,这道题我觉得跟家有难度。我选择设置变量min和result。min是已经遍历过的最小值,result是现在的值和最小值之差的最大值,以此来获得答案。
代码:#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() == 0) return 0;
int re = 0;
int min = prices[0];
for (int i = 1; i < prices.size(); i++) {
if (prices[i] < min) min = prices[i];
if (re < prices[i] - min) re = prices[i] - min;
}
return re;
}
};
0 0
- 【LeedCode】121.Best Time to Buy and Sell Stock
- 【leedcode】121. Best Time to Buy and Sell Stock
- [LeedCode OJ]#121 Best Time to Buy and Sell Stock
- 【leedcode】122. Best Time to Buy and Sell Stock II
- 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
- Language Model 论文阅读笔记
- webpack 多页面模版
- 今人愁真
- 从一个简单的聊天程序SimpleChat看VPN技术
- 内网安全——利用NSA Smbtouch批量检测内网
- 【leedcode】121. Best Time to Buy and Sell Stock
- Java实现3DES对称加密
- Golang适合高并发场景的原因分析
- simpleCNN 训练 cifar-10 数据集
- 企业海量数据搜索服务器架构图
- 忆同窗
- PCIe设备发现过程
- 用C++玩转矩阵
- Bootstrap打造特色进度条