LeetCode 121: Best Time to Buy and Sell Stock
来源:互联网 发布:java从入门到精通 编辑:程序博客网 时间:2024/06/05 07:05
题目链接:
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
描述
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.
输入
输入一个数组。
输出
最大利润。
样例输入
[7, 1, 5, 3, 6, 4][7, 6, 4, 3, 1]
样例输出
50
算法思想:
刚开始使用两次循环遍历,结果超时,后来改为一次循环,AC通过。
一次循环,使用mini记录之前最小的价格,ans之前的结果,如果当前数小于mini,则更新mini为当前数,否则如果ans小于prices[i] - mini,则更新ans。循环遍历完,ans存放的即为最大利润值。
源代码
class Solution {public: int maxProfit(vector<int>& prices) { int sz = prices.size(); if (sz == 0) return 0; int ans = 0, mini = prices[0]; for (int i = 0; i < sz; i++) { if (prices[i] < mini) { mini = prices[i]; } else { if (ans < prices[i] - mini) { ans = prices[i] - mini; } } } return ans; }};
算法复杂度:
由源代码可知,算法只有一次循环,故时间复杂度为O(n)。
阅读全文
0 0
- LeetCode 121: Best Time to Buy and Sell Stock
- LeetCode(121)Best Time to Buy and Sell Stock
- LeetCode 121 Best Time to Buy and Sell Stock
- LeetCode: Best Time to Buy and Sell Stock [121]
- LeetCode 121 Best Time to Buy and Sell Stock
- [leetcode 121] Best Time to Buy and Sell Stock
- Leetcode NO.121 Best Time to Buy and Sell Stock
- LeetCode 121 Best Time to Buy and Sell Stock
- LeetCode(121) Best Time to Buy and Sell Stock (Java)
- leetcode-121 Best Time to Buy and Sell Stock
- leetcode || 121、Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock - LeetCode 121
- leetcode#121 Best Time to Buy and Sell Stock
- Leetcode 121 Best Time to Buy and Sell Stock
- Leetcode #121 Best Time to Buy and Sell Stock
- leetcode 121: Best Time to Buy and Sell Stock
- leetcode: (121) Best Time to Buy and Sell Stock
- 121 Best Time to Buy and Sell Stock [Leetcode]
- eclipse git报错git The current branch is not configured for pull No value for key branch.master.merge
- HDOJ 1215 七夕节
- Linux中的自动安装脚本
- 2017-10-31每日一练
- 刷题——5.5
- LeetCode 121: Best Time to Buy and Sell Stock
- 批处理作业问题——分支限界法
- 重命名UE4项目
- 译文及题解 电话线Telephone Wire(动态规划)
- 关于未来,仅供参考
- 第一次实验
- vue组件通信
- Android基础复习(二)
- 每日练习20171031