问题
given a series of stock prices in an array. Pick when to buy and when to sell to gain max profit. from one website i got something like this-ef maxprofit(prices):
buydate, selldate = 0, 0
maxprof = 0 minprice = prices[0] mindate = 0
for d, p in enumerate(prices[1:]): if p < minprice: minprice = p mindate = d + 1 continue
prof = p - minprice
if prof > maxprof: maxprof = prof buydate, selldate = mindate, d + 1
return (buydate, selldate), maxprof
but i think..we should consider negative prices too..isn't? any other solution or comments are most welcome
回答1:
Ideally you want to buy stocks when they're at their lowest and sell when they're highest. So figure out where the peaks and the troughs are in your data and those are your sell and buy points, respectively.
This is as simple as going through the data set, looking at two adjacent points at a time, and keeping track of the current "trend" (whether or not the market is going up or down). If the trend was going up and the price fell, then you should sell on the day before it fell. On the other hand, if the trend was going down and the price rose, you should buy on the day before it rose.
回答2:
Since you have the history and there appears to be no penalty for a transaction, simply take the derivative of the prices and buy when d/dx goes from negative to positive and sell when it goes from positive to negative.
This way you are buying before every gain and selling before every loss.
回答3:
This is a code in java for the above problem which calculates the max profit
class Solution {
public int solution(int[] a) {
if(a==null || a.length==0 || a.length==1)
{
return 0;
}
int buyDay=0;
int sellDay=0;
int profit=0;
for(int i=1;i<a.length;i++)
{
int diff=0;
if(a[buyDay]>a[i])
{
buyDay=i;
}
else if(a[sellDay]<a[i])
{
sellDay=i;
}
if(sellDay<buyDay)
sellDay=buyDay;
diff=a[sellDay]-a[buyDay];
if(diff>profit)
{
profit=diff;
}
}
return profit;
}
}
来源:https://stackoverflow.com/questions/6666776/given-a-series-of-stock-prices-in-an-array-pick-when-to-buy-and-when-to-sell-to