[Leetcode 121, medium] Best Time to Buy and Sell Stock I
来源:互联网 发布:非线性优化的优缺点 编辑:程序博客网 时间:2024/06/05 10:00
Problem:
Say you have an array for which the ith element is the price of a given stock on day i.
(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.
Solutions:
C++:
(I)
int maxProfit(vector<int>& prices) { int max_profit = 0; vector<int> profits; profits.push_back(0); for(int i = 1; i < prices.size(); ++i) profits.push_back(prices[i] - prices[i - 1]); int sum_profits = 0; for(int i = 0; i < profits.size(); ++i) { sum_profits += profits[i]; if(sum_profits < 0) sum_profits = 0; else if(sum_profits > max_profit) max_profit = sum_profits; } return max_profit; }
Java:
Python:
0 0
- [Leetcode 121, medium] Best Time to Buy and Sell Stock I
- LeetCode 121 -- Best Time to Buy and Sell Stock I
- LeetCode 121 Best Time to Buy and Sell Stock I
- Leetcode: Best time to buy and sell a stock I
- leetcode-Best Time to Buy and Sell Stock I II
- leetcode Best Time to Buy and Sell Stock(I~III)(*)
- [Leetcode] Best Time to Buy and Sell Stock I | III
- [leetcode]Best Time to Buy and Sell Stock I&II
- LeetCode:123. Best Time to Buy and Sell Stock I
- 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)
- SecureCRT 5.2.2的注册码
- android多分辨率适配(一)
- ubuntu10.04配置ssh
- 黑马程序员——java中file类的一些总结
- 低功耗蓝牙4.0BLE编程-nrf51822开发(9)
- [Leetcode 121, medium] Best Time to Buy and Sell Stock I
- unity3d 在UGUI中制作自适应调整大小的滚动布局控件
- Android模仿三星手机系统滑动条滑动时滑块变大的特效
- 用Keil MDK开发TQ2440裸机程序入门教程
- 用 if 和 switch 语句实现多分枝结构
- 深度优先算法、广度优先算法 与 图的遍历
- jar、war、ear包区别
- 性能测试结果分析
- jenkins配置