码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_121_Best Time to Buy and Sell Stock

时间:2015-02-06 13:22:16      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:array   c++   leetcode   dp   

版权所有,欢迎转载,转载请注明出处,谢谢技术分享


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.

//vs2012测试
#include<iostream>
#include<vector>

using namespace std;

#define N 2
#define INF 0x6FFFFFFF

class Solution {
public:
    int maxProfit(vector<int> &prices) 
	{
		if(prices.size()==0)
			return 0;
		int minprices=INF;
		int maxpro=0;
        for(int i=0; i<prices.size(); i++)
		{
			minprices = min(minprices , prices[i]);
			maxpro = max(maxpro, prices[i]-minprices);
		}
		return maxpro;
    }
};

int main()
{
	int a;
	vector<int> prices;
	for(int i=0; i<N; i++)
	{
		cin>>a;
		prices.push_back(a);
	}
	Solution lin;
	cout<<lin.maxProfit(prices)<<endl;
}

//方法一:自测Accepted
#define INF 0x6FFFFFFF
class Solution {
public:
    int maxProfit(vector<int> &prices) {
		if(prices.size()==0)
			return 0;
		int minprices=INF;
		int maxpro=0;
        for(int i=0; i<prices.size(); i++)
		{
			minprices = min(minprices , prices[i]);
			maxpro = max(maxpro, prices[i]-minprices);
		}
		return maxpro;
    }
};


leetcode_121_Best Time to Buy and Sell Stock

标签:array   c++   leetcode   dp   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/43562071

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!