Leetcode--Best Time to Buy and Sell Stock III
2015-10-11 12:09
591 查看
Problem Description:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
分析:
依照题意。要求依据每天的股票价格,交易两次得到最大的利润。直接的想法就是利用分治法。从前往后循环依次将数组分为前后两个股票价格序列,分别得到最大的利润,将两者相加得到两次交易的最大利润。时间复杂度O(n^2),提交果然超时了。
代码例如以下:
看了discus以后发现事实上可以在O(n)时间内将前后两部分的最大利润求出来,详细实现就是用两个数组分别存储从前往后和从后往前两次遍历时每天的最大利润,最后得到两次交易可以获得的最大利润。
详细代码例如以下:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
分析:
依照题意。要求依据每天的股票价格,交易两次得到最大的利润。直接的想法就是利用分治法。从前往后循环依次将数组分为前后两个股票价格序列,分别得到最大的利润,将两者相加得到两次交易的最大利润。时间复杂度O(n^2),提交果然超时了。
代码例如以下:
class Solution { public: int profit(vector<int> &vec,int beg,int last) { int res=0; if(beg==last) return res; int min=vec[beg]; for(int i=beg+1;i<=last;++i) { if(vec[i]>min) { int temp=vec[i]-min; if(temp>res) res=temp; } else min=vec[i]; } return res; } int maxProfit(vector<int> &prices) { int res=0; int n=prices.size(); if(n<=1) return res; for(int i=1;i<n-1;i++) { int res1=profit(prices,0,i); int res2=profit(prices,i+1,n-1); if((res1+res2)>res) res=res1+res2; } return res; } };
看了discus以后发现事实上可以在O(n)时间内将前后两部分的最大利润求出来,详细实现就是用两个数组分别存储从前往后和从后往前两次遍历时每天的最大利润,最后得到两次交易可以获得的最大利润。
详细代码例如以下:
class Solution { public: int maxProfit(vector<int> &prices) { int res=0; int n=prices.size(); if(n<=1) return res; vector<int> front(n,0); vector<int> back(n,0); int minp=prices[0]; int maxp=prices[n-1]; for(int i=1;i<n;i++) { if(prices[i]>minp) front[i]=prices[i]-minp; else minp=prices[i]; } for(int i=n-2;i>=0;i--) { if(prices[i]>maxp) maxp=prices[i]; back[i]=max(maxp-prices[i],back[i+1]); if(front[i]+back[i]>res) res=front[i]+back[i]; } return res; } };
相关文章推荐
- Some Life Tricks I Noticed
- TCP/IP、Http、Socket的区别
- 2016联想校招图形图像软件工程师在线笔试真题
- HDOJ 题目1576 A/B(拓展欧几里得求乘法逆元)
- 【人工智能】农夫过河问题
- POJ-2039
- HDU5501/BestCoder Round #59 (div.2)The Highest Mark dp+贪心
- C#使用基类的引用 and 虚方法和覆写方法
- 定时自动启动任务crontab命令用法
- 条件编译(#ifdef #else #endif #if)
- C#内存管理-栈堆/回收器托管/非托管资源释放/指针的应用
- 【小白装系统】——U盘法简介
- BZOJ 1061: [Noi2008]志愿者招募(最小费用最大流)
- 分西瓜(DFS)
- iOS_Quartz 2D绘图
- PHP计划任务:如何使用Linux的Crontab执行PHP脚本
- win 10 右键新建offic失效问题
- iOS 视频播放基础
- 服 务 器 时 间 设 置
- eclipse中文乱码修改新方法,在修改了所有的utf-8都没有用就这样修改