LeetCode OJ 121 Best Time to Buy and Sell Stock
2015-10-19 12:33
281 查看
题目:
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.
难度:medium
思路: 动态规划问题。i处能够获得的最大利润i之后的最大值-i处的price。循环通过倒序可得O(n)的解法
代码如下
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.
难度:medium
思路: 动态规划问题。i处能够获得的最大利润i之后的最大值-i处的price。循环通过倒序可得O(n)的解法
代码如下
class Solution { public: int maxProfit(vector<int>& prices) { if(prices.size()<=1) return 0; int maxPrice = prices[prices.size()-1]; int maxprofit=0; for(int i=prices.size()-1;i>=0;i--){ maxPrice = max(maxPrice,prices[i]); maxprofit=max(maxPrice-prices[i],maxprofit); } return maxprofit; } };
相关文章推荐
- 链表之求链表倒数第k个节点
- 推送通知(远程推送)(服务器PushMeBaby)(iOS SDK)(JPush)
- 服务端数据库和程序的版本不一致
- 知名博客地址
- android项目的结构和布局
- MongoDB的备份(mongodump)与恢复(mongorestore)
- 支持gif的图片预览控件
- 广播两种注册类型的区别
- JAVA调用易信接口向指定好友推送消息(一)背景需求
- 数塔2(dp)
- *自定义布局的Toast和Dialog
- ATPDraw v5.7 1CD电力电路仿真模拟软件
- 支持gif的图片预览控件
- ATPDraw v5.7 1CD电力电路仿真模拟软件
- Tutorial: Loading and parsing external XML and JSON files with Unity
- 程序员跳槽神级攻略
- SYSAUX表空间大于33G问题处理
- redis(二)--命令
- 让程序员跳槽的非钱原因
- C#学习日记26---接口(interface)类型