您的位置:首页 > 其它

【leetcode】Best Time to Buy and Sell Stock

2015-04-01 12:51 232 查看

Best Time to Buy and Sell Stock

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.

如果只能买卖一次的话,先买入股票,然后再卖出,这样的话,就寻找差值最大的两天即可

超时算法

int maxProfit(int prices[], int n){
int proft=0;
int i,j;
for(i=0;i<n;i++)
{
for(j=n-1;j>i;j--)
{
proft=(prices[j]-prices[i])>proft?(prices[j]-prices[i]):proft;
}
}
return proft;
}


正确算法

只需要找出最大的差值即可,即 max(prices[j] – prices[i]) ,i < j。一次遍历即可,在遍历的时间用遍历low记录 prices[o….i] 中的最小值,就是当前为止的最低售价,时间复杂度为 O(n)。

int maxProfit(int prices[], int n){
if(n==0) return 0;
int profit=0;
int low=prices[0];
for(int i=1;i<n;i++)
{
if(prices[i]<low) low=prices[i];
else if(prices[i]-low>profit) profit=prices[i]-low;
}
return profit;
}


Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

本题一定要注意,可以买卖多次,一个股票一天内就可以买卖多次,既可以买又可以卖,所以下面的解法是可以的:如果只能买或者卖的话,可能考虑得就比较复杂。

int maxProfit(int prices[], int n){
int profit=0;
if(n==0||n==1) return 0;
for (int i=1;i<n;i++)
{
if(prices[i]-prices[i-1]>0)
profit=profit+prices[i]-prices[i-1];
}
return profit;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: