leetcode_122——Best Time to Buy and Sell Stock II(贪心算法)
2015-06-22 16:58
417 查看
Best Time to Buy and Sell Stock II
Total Accepted: 49554 Total Submissions: 129459My SubmissionsQuestion Solution
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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Hide Tags
Array Greedy
Have you met this question in a real interview?
Yes
这道题采用贪心算法的策略,要想整体最优,先要使得局部达到最优才行,这个就是先计算每个的局部最优
#include<iostream> #include<vector> using namespace std; int maxProfit(vector<int>& prices) { if(prices.empty()) return 0; vector<int> vec=prices; int len=vec.size(); if(len==1) return 0; vec[0]=0; for(int i=1;i<len;i++) vec[i]=prices[i]-prices[i-1]; int maxnum=0; int k=0; while(k<len) { int temp=0; while(1) { if(k>=len||vec[k]<0) break; temp+=vec[k]; k++; } maxnum+=temp; k++; } return maxnum; } int main() { }
相关文章推荐
- Axure实现淡入淡出效果,axure实现淡入淡出
- 压缩文件gzip zcat
- 给定入栈序列1到n,输出所有可能的出栈序列
- Android Scroller类的详细分析
- android配置
- JavaMail实现收发邮件——(一)相关概念概述
- jquert结合原生javascript实现的checkbox全选与全不选
- Android 项目中文件夹的作用(初识)
- android中string.xml中%1$s、%1$d等的用法
- 如何Enable FireFox里的Java Plugin
- 场景调研
- Yii restfull添加新的ACTION方法
- Chrome与Firefox对于时间处理的不同
- poj 1731 Orders
- 从线性回归谈到岭回归lasso回归再到结构风险最小化和参数缩减
- Liunx_4.4_有名管道
- cocos2dx项目打包APK环境安装
- 探索MySQL高可用架构之MHA(3)
- [BZOJ1715][Usaco2006 Dec]Wormholes 虫洞
- Java, just a language (三)