public int maxProfit(int[] prices) {

    int sum = 0;
    int buyPrice = 0;
    boolean hold = false;

    for (int i = 1 ; i < prices.length ; i++) {
      int diff = prices[i] - prices[i - 1];

      if (hold && diff < 0) {
        hold = false;
        sum += prices[i - 1] - buyPrice;
      } else if (!hold && diff > 0) {
        hold = true;
        buyPrice = prices[i - 1];
      }
    }

    if (hold) {
      sum += prices[prices.length - 1] - buyPrice;
    }
    return sum;
  }