Best Time to Buy and Sell Stock II

MediumArrayDynamic ProgrammingGreedy

Solution

export function maxProfitII(prices: number[]): number {
  let answer = 0;
  const stack: number[] = [];
  for (const price of prices) {
    const minPrice = stack.pop();
    if (minPrice !== undefined && minPrice < price) {
      answer += price - minPrice;
    }
    stack.push(price);
  }
  return answer;
}