[LeetCode] Best Time to Buy and Sell Stock
来源:互联网 发布:js验证密码的正则 编辑:程序博客网 时间:2024/04/28 14:37
题目:
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.
解析:
数组右边的数减去左边的数的数对之差最大。
动态规划求解
maxDiff[i] >= prices[j] - prices[i] (j>i)maxDiff = max( maxDiff, maxMinuend-cur )
class Solution {public:int maxProfit(vector<int> &prices) {if(prices.size()<2)return 0;int length = prices.size();int max = prices.back();int maxDiff = max-prices[length-2]>0?max-prices[length-2]:0;for(int i = length-3;i>=0;i--){if(prices[i+1]>max){max=prices[i+1];}int curDiff= max-prices[i];if(curDiff>maxDiff)maxDiff=curDiff;}return maxDiff;}};
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
- AWK 使用与或匹配
- 《视频解密》中文版(第四版)第八章 NTSC,PAL和SECAM概述(第一部分)
- java常量池技术
- Axis 配置webService 配置文件未找到
- Android在代码中实现重启(reboot)
- [LeetCode] Best Time to Buy and Sell Stock
- C51单片机复习资料
- 单元测试OCUnit+xctool
- 9 cocos2d-x CCControlSlider (滑动条)
- 如何:对 SharePoint 列表项隐藏 ECB 中的菜单项
- ASIHTTPRequest类库简介和使用说明
- 盘点谷歌旗下的那些逆天机器人
- 高效Linux用户需要了解的命令行技能
- sqlite入门基础(二):sqlite3_get_table,sqlite3_free_table