#149 Best Time to Buy and Sell Stock
来源:互联网 发布:数据库接口怎么开发 编辑:程序博客网 时间:2024/05/21 15:04
题目描述:
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.
Example
题目思路:Given array [3,2,3,1,2]
, return 1
.
这题就是要找一个最大值和一个最小值,使得他俩的差最大。并且,最小值要在最大值的左边。
这里可以预先算两个vector:一个left_min,求的是i往左看所有数的最小值;一个right_max,求得是i往右看所有数的最大值。然后,我们遍历一遍数组,对于每个i,看right_max[i] - left_min[i],求出所有i中的最大值就是答案了。
Mycode(AC = 60ms):
class Solution {public: /** * @param prices: Given an integer array * @return: Maximum profit */ int maxProfit(vector<int> &prices) { // write your code here if (prices.size() <= 1) return 0; vector<int> left_min(prices); vector<int> right_max(prices); // get min number at left of i for (int i = 1; i < prices.size(); i++) { left_min[i] = min(left_min[i - 1], prices[i]); } // get max number at right of i for (int i = prices.size() - 2; i >= 0; i--) { right_max[i] = max(right_max[i + 1], prices[i]); } int profit = 0; for (int i = 0; i < prices.size(); i++) { profit = max(profit, right_max[i] - left_min[i]); } return profit; }};
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
- 大牛解密阿里云直播技术平台
- ubuntu出现您的当前网络有.local域
- 不错的资料库
- CGAL 编译指南
- Find number of subsets with equal sum
- #149 Best Time to Buy and Sell Stock
- Android使用fitsSystemWindows属性实现–状态栏【status_bar】各版本适配方案
- JAVA 数据类型转换
- Cannot load from mysql.proc. The table is probably corrupted 问题解决
- Android intent-fileter简介
- Java IO小结
- ROM、RAM、DRAM、SRAM和FLASH的区别
- GB28181开流SDP各个字段汇总整理
- 【机器学习】推导支持向量机SVM二分类