LeetCode 121 Best Time to Buy and Sell Stock(股票买入卖出的最佳时间)
来源:互联网 发布:python程序设计答案 编辑:程序博客网 时间:2024/03/29 18:42
翻译
话说你有一个数组,其中第i个元素表示在第i天的股票价格。如果你被只被允许最多一次交易(例如,买入然后卖出一个股票),设计一个算法并找出最大利润。
原文
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.
分析
首先设定最大利润和最小利润:
如果当前这一天的股票价格比最低价格还小,那就把最低价格设置为这一天的股票价格。
为什么要算这个价格了,当然是为了算最大利润铺路了。
如果最大利润比当天价格减掉最低价格还要低,那就把最大利润设置成当天价格减去最低的价格。
代码
class Solution {public: int maxProfit(vector<int>& prices) { size_t size = prices.size(); if (size <= 1) return 0; int min = INT_MAX, max = INT_MIN; for (int i = 0; i < size; ++i) { if (prices[i] < min) min = prices[i]; if (max < prices[i] - min) max = prices[i] - min; } return max; }};
2 0
- LeetCode 121 Best Time to Buy and Sell Stock(股票买入卖出的最佳时间)
- Best Time to Buy and Sell Stock 最佳时间买入卖出股票(一次买入卖出) @LeetCode
- LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
- LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
- 最佳时间买入卖出股票 Best Time to Buy and Sell Stock LeetCode
- Best Time to Buy and Sell Stock II 最佳时间买入卖出股票(多次买卖)@LeetCode
- Best Time to Buy and Sell Stock III 最佳时间买入卖出股票(最多两次买卖)@LeetCode
- LeetCode-121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)
- LeetCode 121. Best Time to Buy and Sell Stock--股票买入后再卖出,求最大收益,最多交易一次
- 【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】
- LeetCode OJ 之 Best Time to Buy and Sell Stock (买卖股票的最佳时间)
- [LeetCode] Best Time to Buy and Sell Stock IV 买卖股票的最佳时间之四
- LeetCode OJ 之 Best Time to Buy and Sell Stock II (买卖股票的最佳时间 2)
- LeetCode OJ 之 Best Time to Buy and Sell Stock III (买卖股票的最佳时间 - 三)
- Best Time to Buy and Sell Stock 【最佳买卖股票的时间】【容易】
- 123/188/309.Best Time to Buy and Sell Stock 买股票的最佳时间
- 122. Best Time to Buy and Sell Stock II 最佳买卖股票的时间
- leetcode 122. Best Time to Buy and Sell Stock II 股票买卖最佳时间(二)
- c#往SQL Server写Emoji表情
- 从Android运行时出发,打造我们的脱壳神器
- javascript机制致错
- Android 简易版天气预报app的现实(4)
- Asyntask异步任务
- LeetCode 121 Best Time to Buy and Sell Stock(股票买入卖出的最佳时间)
- 认识UART接口
- 总结
- 深搜格式
- iOS应用架构谈(一):架构设计的方法论
- redis主从集群搭建及容灾部署(哨兵sentinel)
- OpenGL绘制一个点、线、多边形
- Android Studio常用快捷键整理(陆续添加)
- 支付漏洞总结 / 在线支付流程安全分析