【Leetcode】Best Time to Buy and Sell Stock
来源:互联网 发布:c语言流程图规范 编辑:程序博客网 时间:2024/06/05 02:31
题目:
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) { int min_date=0,min_price=INT_MAX,max_profit=0; for(int i=0;i<prices.size();i++){ if(prices[i]<min_price){ min_price=prices[i]; min_date=i; } if(i>min_date&&prices[i]-min_price>max_profit)max_profit=prices[i]-min_price; } return max_profit; }};
0 0
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode 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: Best time to buy and sell a stock I
- Leetcode: Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] 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 : Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock
- mybatis3+spring3整合方式
- [android]获取各应用的启动次数和运行时间
- js确认是否删除。
- java--Set
- C++ Primer Plus 第六版课后编程答案 2.1-2.5
- 【Leetcode】Best Time to Buy and Sell Stock
- Android学好Shape不再依赖美工
- 【小白笔记】PHP学习之路 (15) --数组(5)
- Hibernate get和load区别
- Ubuntu关闭进程
- PL/SQL 实现行列转换
- IOS高访新浪微博界面(讲解如何自定义UITableViewCell,处理@#链接 特殊字符)
- 动态修改jar包中xml的Demo实现
- 心