您的位置:首页 > 编程语言 > Java开发

LeetCode:Best Time to Buy and Sell Stock I & II & III

2014-03-27 14:24 489 查看
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.

比较简单,遍历一遍,记录最小值和与最小值的最大差值,最后返回最大差值。

public class Solution {
public int maxProfit(int[] prices) {
int len=prices.length;
if(len==0) return 0;
int minn=prices[0],profit=0;
for(int i=1;i<len;i++)
{
if(prices[i]<minn)
{
minn=prices[i];
continue;
}
if(prices[i]-minn>profit)profit=prices[i]-minn;
}
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).
与第一个不同的是允许多次买卖,因此只要是递增序列就就将差值累计,最后得到结果

public class Solution {
public int maxProfit(int[] prices) {
int len=prices.length;
int i,res=0;
if(len<1)return 0;
for(i=0;i<len-1;i++)
{
if(prices[i]<prices[i+1])res+=prices[i+1]-prices[i];
}
return res;
}
}


Best Time to Buy and Sell Stock III

 

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 at most two transactions.

Note:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

可以买两次,如果可以找到一个点刚好使得麦麦两次股票都在这个点两边,且买卖收益之和最大, 又回归到了第一个题目,思路简单:

public class Solution {
public int divProfit(int [] prices,int low,int hight)
{
int minn=prices[low],profit=0;
for(int i=low;i<=hight;i++)
{
if(minn>prices[i])
{
minn=prices[i];
continue;
}
if(profit<prices[i]-minn)profit=prices[i]-minn;

}
return profit;
}

public int maxProfit(int[] prices) {
int len=prices.length;
if(len<=1)return 0;
int maxn=0,profit;
for(int i=1;i<len-1;i++)
{
profit=divProfit(prices,0,i)+divProfit(prices,i,len-1);

if(maxn<profit)maxn=profit;
}
return maxn;
}
}
在此之上进行改进,记录中间数据,减少遍历次数:

public class Solution {
public int maxProfit(int[] prices) {
final int len=prices.length;
if(len<=1)return 0;
int [] maxHead =new int [len];
maxHead[0]=0;
int minPrice = prices[0], maxProfit = 0;
for(int i=1;i<len;i++)
{
minPrice=Math.min(minPrice,prices[i-1]);
if(maxProfit<prices[i]-minPrice)
{
maxProfit=prices[i]-minPrice;
maxHead[i]=maxProfit;
}
}
int maxPrice=prices[len-1];
int profit=maxHead[len-1];
maxProfit=0;
for(int i=len-2;i>=0;i--)
{
maxPrice=Math.max(maxPrice,prices[i+1]);
if(maxProfit<maxPrice-prices[i])
{
maxProfit=maxPrice-prices[i];
}
if(profit<maxHead[i]+maxProfit)
{
profit=maxHead[i]+maxProfit;
}
}
return profit;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息