2015年10月11日星期日

stock max profit with commision fee

今天看到一个facebook的面经follow up,leetcode的sell stock II但是每完成一次买卖都要收手续费,问这种情况下这最佳收益是多少下面是sell stockII的题目

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 int stock5(int[] prices, int fee) {
int n = prices.length;
int dp[][] = new int[n][2];
dp[0][0] = -prices[0];
dp[0][1] = 0;
// 0 is buy, 1 is sell
for (int i = 1; i < n; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee);
}
return dp[n - 1][1];
}
http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=140876&extra=page%3D1%26filter%3Dsortid%26sortid%3D311%26searchoption%5B3046%5D%5Bvalue%5D%3D14%26searchoption%5B3046%5D%5Btype%5D%3Dradio%26sortid%3D311
 

private int stock(int prices[], int fee) {
    int afterBuy = -prices[0];
    int afterSell = 0;
    for (int i = 1; i < prices.length; i++) {
      int oldBuy = afterBuy;
      int oldSell = afterSell;
      afterBuy = Math.max(oldBuy, oldSell - prices[i]);
      afterSell = Math.max(oldSell, oldBuy + prices[i] - fee);
    }
    return afterSell;
  }

没有评论:

发表评论