Practice/Oracle/Leetcode 122. Best Time to Buy and Sell Stock II
CodingOptional
You are given an array of integers representing stock prices on consecutive days. Each element prices[i] indicates the stock price on day i.
Your goal is to maximize your profit by strategically buying and selling the stock. You can perform as many transactions as you want (buy once and sell once counts as one transaction), but you must follow these rules:
Calculate and return the maximum profit you can achieve. If no profit is possible, return 0.
Example 1:
Input: prices = [7, 1, 5, 3, 6, 4] Output: 7 Explanation: Purchase on day 2 at price 1, sell on day 3 at price 5 for profit of 4. Then purchase on day 4 at price 3, sell on day 5 at price 6 for profit of 3. Total profit: 4 + 3 = 7
Example 2:
Input: prices = [1, 2, 3, 4, 5] Output: 4 Explanation: Purchase on the first day at price 1, sell on the last day at price 5. This gives a profit of 4. This is equivalent to capturing every daily price increase.
Example 3:
Input: prices = [7, 6, 4, 3, 1] Output: 0 Explanation: Prices only decrease, so no profitable transaction exists. Return 0.