# Leetcode 188 - Best time to buy and sell stock IV

`Note`

- Basically we need to find the pattern from
`III`

. - To initialize the
`dp`

array, it’s not hard to find that`even index`

needs to be`0`

and`odd index`

needs to be`prices[0]`

. - To iterate through
`i`

, two sitations based on i- When i is even,
`dp[i][j] = Math.max(dp[i-1][j-1] + prices[i], dp[i-1][j]);`

- When i is odd,
`dp[i][j] = Math.max(dp[i-1][j-1] - prices[i], dp[i-1][j])`

- When i is even,

You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k.

Find the maximum profit you can achieve. You may complete at most k transactions.

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

**Example**

1 | Input: k = 2, prices = [2,4,1] |

1 | /** |