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

LeetCode31:Best Time to Buy and Sell Stock

时间:2014-12-26 16:41:15      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:leetcode   dynamic programming   

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.

// Source : https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/  
// Author : Chao Zeng    
// Date   : 2014-12-26  
class Solution {
public:
    int maxProfit(vector<int> &prices) {
		int n = prices.size();
		if (n == 0)
			return 0;
		int mp[n];//表示以prices[i]结尾的max profit
		int minnumber = prices[0];
		memset(mp,0,sizeof(mp));
		for (int i = 1; i < n; i++){
			if (minnumber > prices[i])
				minnumber = prices[i];
			int dis = prices[i] - minnumber;
			if (mp[i-1] < dis)
				mp[i] = dis;
			else
				mp[i] =mp[i-1];
		}
		return mp[n-1];
    }
};


LeetCode31:Best Time to Buy and Sell Stock

标签:leetcode   dynamic programming   

原文地址:http://blog.csdn.net/hnuzengchao/article/details/42173053

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