Best Time to Buy and Sell Stock
2015-11-29 11:18
218 查看
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.
算法导论原题,股票买入卖出的最大利益-->数组中后面的元素与前面的元素的最大差值-->转换为连续子数组最大和
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>& diff,int diffSize){ int curMax=0; int res = 0; for(int i=0;i<diffSize;i++){ if(i==0){ curMax = diff[i]; res = diff[i]; }else{ curMax = max(curMax+diff[i],diff[i]); res = max(res,curMax); } } return res; } int maxProfit(vector<int>& prices) { int pricesSize = prices.size(); vector<int> diff(pricesSize,0); for(int i=1;i<pricesSize;i++){ diff[i] = prices[i]-prices[i-1]; } return maxProfit(diff,pricesSize); } };
相关文章推荐
- 话题15 异曲同工--交换变量的3种方式
- 整理Javascript基础语法学习笔记
- 第一次spring,第三天。
- linux shell中的变量PS1------定制linux shell提示符
- 基于android的Socket通信
- [LeetCode]Group Shifted Strings
- crontab,linux中创建定时任务与取消
- [Sort]冒泡排序
- Valid Sudoku
- Android应用去掉标题栏(Android Studio)
- Android使用HTTP协议访问网络
- HDU5573 Binary Tree
- J2SE基础夯实系列之List中的数据如何根据对象的某一个或多个字段排序引出Comparable和comparator的使用
- Andriod学习笔记2:“Your content must have a ListView whose id attribute is 'android.R.id.list'”问题的解决办法
- 第一个spring,第一天。
- WEB java(SSH)日记(2)
- TOC 系统思考培训日记2015-11-28
- 链表反转(C++版)
- 滑动门JS
- great-computer-programming-quotes