Best Time to Buy and Sell Stock
来源:互联网 发布:淘宝网app客户端 编辑:程序博客网 时间:2024/06/09 15:49
Say you have an array for which the ith element is the price of a given stock on dayi.
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.
(1)思路比较简单,主要是对于每一个位置求他左边数值的最小值(包括他本身),以后他右边数值的最大值。
(2)循环上面的求解,然后输出一个最大值
#include <iostream>#include <vector>using namespace std;int maxProfit(vector<int> &prices) {size_t len = prices.size();if(len == 0 || len == 1)return 0;vector<int> minLeft(len,0);vector<int> maxRight(len,0);int profit = 0;minLeft[0] = (prices.at(0));maxRight[len-1] = (prices.at(len-1));for(size_t i=1;i<len;i++){if(prices.at(i) < minLeft.at(i-1))minLeft[i] = prices.at(i);elseminLeft[i] = minLeft.at(i-1);}for(int i=len-2;i>=0;i--){if(prices.at(i) > maxRight.at(i+1))maxRight[i] = prices.at(i);elsemaxRight[i] = maxRight.at(i+1);}for(size_t i = 0;i<len-1;i++){int temp = maxRight.at(i+1) - minLeft.at(i);if(temp > profit){profit = temp; }}if(profit <= 0)return 0;return profit;}int main(void){vector<int> prices;prices.push_back(1);prices.push_back(5);prices.push_back(3);prices.push_back(7);prices.push_back(6);prices.push_back(4);prices.push_back(2);prices.push_back(3);cout << maxProfit(prices) << endl;system("pause");return 0;}
0 0
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time To Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- linux中断--中断原理分析
- 小黑小波比.Ubuntu下hoststool安装与使用为上谷歌安卓官网
- 实现蝴蝶翩翩飞舞的效果
- Notepad++不打开最近打开的文件
- 《私房菜》3rd 笔记0. 目录
- Best Time to Buy and Sell Stock
- linux中断--内核中断编程
- B - The Large Family+暴力枚举
- SDWebImage的使用
- TCP/IP数据包格式详解-包括数据链路层的头部
- linux中断--中断嵌套&中断请求丢失
- Hbase简介
- cocos2dx添加第三方库注意事项
- linux中断--中断下半部机制的使用 & 中断编程