标签: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