# Buy Sell Stock Max Profit Coding Question Solution in Java

**Problem statement:**

- You have array of daily rates of the stock, i
^{th}element of the array is the rate of the i^{th}day for the stock. - You can buy and sell only one stock
- You need to find the max profit of the buy and sell transaction.

**Pre-Requisite:**

- We don’t wany defined algorithms like k-means or bst etc to solve this problem.
- We can solve this with simple array and n-times iterations.

**Input:**

How many days of daily rates you have ?

3

Enter the stock rates one by one for 3 days

7

1

10

**Expected Output:**

Max profits you can earn is:

9

**Explanation:**

If we buy the stock on day 1 for 7 then sell on day 2 (buy price: 7 – sell price: 1=6 rupees loss, same way 7-10 = 3 rupees profit)

**If we buy the stock on day 2 at 1 rupee (and sell the same on day 3 at 10 rupees then profit 9 (10-1))**

If we buy the stock on day 3 at 10 rupees then (have to sell for same day so earning is 0 profit).

**So here the max profit is 9**

**Java Coding Solution for Buy Sell Stocks Max Profits Array Question:**

package com.ngdeveloper; import java.util.Scanner; public class BuySellStockMaxProfit { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("How many days of daily rates you have ?"); int totalElements = sc.nextInt(); int[] dailyRates = new int[totalElements]; System.out.println("Enter the stock rates one by one for "+totalElements+" days"); for(int i=0;i<totalElements;i++) { dailyRates[i] = sc.nextInt(); } int maxProfit = maxProfit(dailyRates); System.out.println("Max profits you can earn is:"); System.out.println(maxProfit); } // space complexity is O(1) - we have totally maxProfit and buyAt variables created and only these two needs the storage space in the memory. // time complexity is O(n) - We have to iterate the array atleast once to find the maxProfit. static int maxProfit(int[] dailyRates) { if(dailyRates.length==0) { return 0; } int maxProfit = 0; int buyAt = dailyRates[0]; for(int i=1;i<dailyRates.length;i++) { maxProfit = Math.max(dailyRates[i]-buyAt, maxProfit); if(dailyRates[i] < buyAt) { buyAt = dailyRates[i]; } } return maxProfit; } }

**Program Output:**

How many days of daily rates you have ? 3 Enter the stock rates one by one for 3 days 7 1 10 Max profits you can earn is: 9

**Time & Space Complexity of Buy Sell Stock Solution: **

**Time complexity – O(n)** – based on the number of daily rates or array elements as we need to run the array values atleast once to find the maxProfit.

**Space Complexity – O(1)** – O(1) defines the constant space complexity, meaning we have to store only the buyAt and maxProfit variables and here the number of variables or spaces allocated based on the number of elements in the array. So it is just O(1).