leetCode:121\122\309 股票买入和卖出获取最大收益问题
来源:互联网 发布:javascript 显示隐藏 编辑:程序博客网 时间:2024/04/30 20:34
/**leetCode 121 :动态规划求 最佳买入和卖出股票 给出一组int数组,每个值代表当天股票的价格,你只能买1次并且卖1次,求最大收益 动态规划求解:*/int maxProfit(vector<int>& prices) { if(prices.size()==0) return 0; int buy = INT_MAX; int profit = 0; for(int i=0;i<prices.size();i++){ buy = min(buy,prices[i]); profit = max(profit,prices[i]-buy); } return profit;}
/**leetCode 122 :动态规划求 最佳买入和卖出股票 给出一组int数组,每个值代表当天股票的价格,你可以买入多次并卖出多次,但是买入之前必须先卖出,求最大收益 动态规划求解:*/int maxProfit(vector<int>& prices) { if(prices.size()==0) return 0; int buy = INT_MAX; int profit = 0; int sum = 0; for(int i=0;i<prices.size();i++){ if(buy>=prices[i]){ buy = prices[i]; sum+=profit; profit=0; } if(profit<prices[i]-buy){ profit = prices[i]-buy; } else{ sum+=profit; profit=0; buy = prices[i]; } } sum+=profit; return sum;}
/**leetCode 309:与上面一样,仍然计算股票的最大收益,可以完成多次交易,但是必须在买这个股票之前先卖掉它,在你卖掉股票之后的一天是不能买股票的。交易有三个状态,buy,sell,rest;定义buy[i]是前i天的任意序列以buy结尾的获取的最大利润 sell[i]是前i天的任意序列以sell结尾的获取的最大利润 rest[i]是前i天的任意序列以rest结尾的获取的最大利润 则buy[i] = max(rest[i-1]-prices[i],buy[i-1]); sell[i] = max(buy[i-1]+prices[i],sell[i-1]); rest[i] = max(buy[i-1],sell[i-1],rest[i-1]); 又因为 buy[i]<=rest[i], rest[i]<=sell[i]; 所以 rest[i] = sell[i-1]; 带入最先定义的3个公式: buy[i] = max(sell[i-2]-prices[i],buy[i-1]); sell[i] =max(buy[i-1]+prices[i],sell[i-1]);*/int maxProfit2(vector<int>& prices) { int prebuy =0; int presell = 0; int buy =INT_MIN; int sell=0; for(int price:prices){ prebuy = buy; buy = max(presell-price,prebuy); presell = sell; sell = max(prebuy+price,presell); cout<<prebuy<<" "<<sell<<endl; } return sell;}
0 0
- leetCode:121\122\309 股票买入和卖出获取最大收益问题
- 网易游戏面试--两次股票买入卖出的最大收益
- LeetCode 121. Best Time to Buy and Sell Stock--股票买入后再卖出,求最大收益,最多交易一次
- 股票买入卖出手续费
- LeetCode 121 Best Time to Buy and Sell Stock(股票买入卖出的最佳时间)
- 给出N天的股价,能买入和卖出股票,但是任何时候手上最多持有一份股票.允许交易K次求最多的收益.
- amazon 股票的最佳买入和卖出点
- leetcode 股票收益问题
- Best Time to Buy and Sell Stock 最佳时间买入卖出股票(一次买入卖出) @LeetCode
- LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
- LeetCode 122 Best Time to Buy and Sell Stock II(股票买入卖出的最佳时间 II)
- 买卖股票收益最大问题
- 假如一个数组存储了一个股票,在一天交易窗口内各时间点的股票价格(正整数),只允许一次买入和一次卖出,请提供一个算法,计算出通过买入和卖出可以得到的最大利润
- 假如一个数组存储了一个股票,在一天交易窗口内各时间点的股票价格(正整数),只允许一次买入和一次卖出,请提供一个算法,计算出通过买入和卖出可以得到的最大利润
- 股票的最佳买入卖出时间
- 最佳时间买入卖出股票 Best Time to Buy and Sell Stock LeetCode
- 一段时间内两次买进卖出股票使得收益最大(C++版)
- Best Time to Buy and Sell Stock II 最佳时间买入卖出股票(多次买卖)@LeetCode
- leetcode——46——Permutations
- UML建模学习1:UML统一建模语言简介
- 在Android Studio中使用AIDL实现进程之间的通信
- 系统设计:活动室申请系统
- 版本控制——Git 使用笔记,以及Windows搭建Git服务器
- leetCode:121\122\309 股票买入和卖出获取最大收益问题
- VMware安装linux centos7选择桌面系统
- JavaEE开学随记1
- 面向对象
- BoW词袋模型Bag of Words cpp实现(stable version 0.01)
- java object默认的基本方法
- SGU 146 The Runner(水~)
- 李商隐 无题
- 关于沸点