From 55d2a67a3a5bae519ea4faa5817f86b2db7c80f3 Mon Sep 17 00:00:00 2001 From: Disha Patel Date: Tue, 4 Nov 2025 11:10:57 -0600 Subject: [PATCH] Competitive-Coding-10 Complete --- BuyandSellStockII.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 BuyandSellStockII.java diff --git a/BuyandSellStockII.java b/BuyandSellStockII.java new file mode 100644 index 0000000..bcd060b --- /dev/null +++ b/BuyandSellStockII.java @@ -0,0 +1,19 @@ +/** + * Approach: The idea is to sell the stock anytime the price goes higher than the buying price to earn max profit + * compare current day price with the previous day price and if it is higher, than sell it and earn profit + * TC: O(n) -> iterate through the prices array + * SC: O(1) -> no additional space required + */ + +class Solution { + public int maxProfit(int[] prices) { + int profit = 0; + + for(int i = 1; i < prices.length; i++){ + if(prices[i] > prices[i-1]){ + profit += prices[i] - prices[i - 1]; + } + } + return profit; + } +} \ No newline at end of file