best time to buy sell stock
http://www.lintcode.com/en/problem/best-time-to-buy-and-sell-stock/
code 2
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if(n == 0)
{
return 0;
}
int lowest_price = INT_MAX;
int profit = 0;
for(int price : prices)
{
lowest_price = min(lowest_price, price);
profit = max(profit, price-lowest_price);
}
return profit;
}
};
code
class Solution {
public:
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
int maxProfit(vector<int> &prices) {
// write your code here
if(prices.size() == 0)
{
return 0;
}
vector<int> shadow;
for(int i = 1; i<prices.size(); i++)
{
shadow.push_back(prices[i] - prices[i-1]);
}
int sum = 0;
int minsum = 0;
int ret = 0;
for(int i = 0; i<shadow.size(); i++)
{
sum += shadow[i];
ret = max(ret, sum-minsum);
minsum = min(minsum, sum);
}
return ret;
}
};