×

Maximizing Profit in Stock Buy Sell in Java

In this tutorial, we will deal with a popular problem, a favourite of interviewers. The problem is named as Maximising profit in stock Buy Sell. we will see certain approaches to solve this problem in java.

Understanding the problem statement

To understand the problem, let’s consider an integer array that shall represent the price of stocks on different dates. The stock can be purchased and sold any amount of times.

Considering an array arr1[]

int arr1[] = {40, 80, 120, 145, 10, 257, 337}

 The value at the 0th position represents the cost of stock on day 1, which is 40 here.

The value at 1st position represents the cost of stock on day 2, which is 80 here.

The value at the 2nd position represents the cost of stock on day 3, which is 120 here.

The value at the 3rdposition represents the cost of stock on day 4, which is145 here.

The value at the 4thposition represents the cost of stock on day 5, which is 10 here.

The value at the 5th position represents the cost of stock on day 6, which is 257 here.

The value at the 6th position represents the cost of stock on day 7, which is 337 here.

Here, the person can buy the stock on any day and sell it on another day. Let’s say he bought it on day 1 and sold it on the 4th day. So, the profit would be 145 - 40 = 105.

Further, the person can buy a stock on day 5 and sell it on the 7th day.

So, the profit would be 337 – 10 = 327.

Thus, the net profit becomes 105 + 327 = 427.

This is the extreme profit that could be gained.

1. Simple Approach

In this approach, the stock is bought on a particular day and is sold on the same day only on the day, selling is profitable. The person has to keep a record of the maximum profit gained in the process.

The subsequent program implements the same approach.

public class MaxProfitStock
{  


// A method that will return the maximum profit  
// which can be earned post buying and selling  of
// the stocks    


public int maximumProfit(int p[], int stk, int ed1)  
{  


// If the stocks cannot be purchased  
if (ed1 <= stk)  
{  
return 0;  
}  


// Initialization of profit variable  
int pro = 0;  


// Finding out the day on which the stock must  
// be purchased 
for (int j = stk; j < ed1; j++)  
{  


// Finding out the day on which the  
// stock must be sold  
for (int i = j + 1; i<= ed1; i++)  
{  


// If buying the stock on ajth day and  
// selling it on anith day seems profitable  
if (p[i] > p[j])  
{  


// Updating the current profit  
// Suppose i = 9, j = 6, ed1 = 8, and stk = 1  
// So, currProfit is profit found is equal to   
// the profit gained when stock is sold on day 6 and purchased on day 3  
// in addition to the profit gained from day 1 to day 5 in addition to the profit gained
// fromday 7 to day 8  
int currProfit = p[i] - p[j] + maximumProfit(p, stk, j - 1) + maximumProfit(p, i + 1, ed1);  


// Updatation of the maximum profit earned so far 
pro = Math.max(pro, currProfit);  
}  
}  
}  
return pro;  
}  


// main method  
public static void main(String argvs[])  
{  
// assigning the price of the stock in an array  
int price[] = { 70, 80, 150, 175, 30, 257, 327 };  
int size = price.length; // computation of the size  of array


System.out.println("The stock price on different days is: ");  


for(int i = 0; i< size; i++)  
{  
// displaying the  price  of a stock
System.out.print(price[i] + " ");  
}  


System.out.println();  
// creation of an object of the class MaxProfitStock
MaxProfitStockobj = new MaxProfitStock();  


int res  =obj.maximumProfit(price, 0, size - 1);  


System.out.print("The maximum profit earned here is: ");  


System.out.print(res);  
}  
}  

Output:

Maximizing Profit in Stock Buy Sell in Java

Time complexity =O(size)

2. Well-organizedApproach

To make the solution even more resourceful, we will take into account an efficient approach where we won’t use recursion, rather we will find the local minima and local maxima The local minima will be considered as the opening index, and the local maxima will be considered as the final index. If local minima are non-existent, then return. We will have to update the solution by updating the tally of buy-sell pairs.

The following code implements this approach. Let us understand that.

// importing an important package  
import java.util.ArrayList;  
// to store the days when to   
// buy and sell the stock  
class Interval1   
{  
int buy1;  
int sell1;  
}  
class MaxProfitStock1  
{  
// A method that calculates the maximum profit using the price of the stock  
void stockBuyandSell(int p[], int size)  
{  
// We cannot purchase and sell the stock on that day  
// Hence, there is no need to proceed further  
if (size == 1)  
{  
System.out.println("No profit is possible since the number of days is equal to 1");  
return;  
}  


int c = 0;  


// the array containing the solution  
ArrayList<Interval1> al = new ArrayList<Interval1>();  


// Traversing through the given array of price   
int j = 0;  
while (j < size - 1)   
{  
// Finding the Local Minima. 
//It is to be noted that the limit is (size - 2) as we are  
// comparing the present element to the subsequent element.  
while ((j < size - 1) && (p[j + 1] <= p[j]))  
{  
j = j + 1;  
}  


// As we reach the end, break since   
// there are no possible solutions ahead
if (j == size - 1)  
{  
break;  
}  


// creating an object of the class interval  
Interval1 in = new Interval1();  
// Store the index of minima  
in.buy1 = j + 1;   
j = j + 1;  




// Finding Local Maxima.
// it is to be noted that the limit is (size - 1) as we   
// have to compare to previous element  
while ((j < size) && (p[j] >= p[j - 1]))  
{  
j = j + 1;  
}  


// store the index for the maxima  
in.sell1 = j;  
al.add(in);  


// Increase the number of buys or sell  
c = c + 1;  
}  


// presenting the solution  
if (c == 0)  
{  
System.out.println("Purchasing the stock on any provided day will hardly make any profit.");  
}  
else  
{  
int res = 0;  
for (int i = 0; i< c; i++)  
{  
System.out.println("Purchase the stock on day: " + al.get(i).buy1  
+ "  "  
+ "Sell the stock on day: " + al.get(i).sell1);  


res = res + (p[(al.get(i).sell1 - 1)] - p[(al.get(i).buy1 - 1)]);  
}  
System.out.println("Hence, the total profit is: " + res);  
}  
return;  
}  
// main method  
public static void main(String argvs[])  
{  
// creation of an object  
MaxProfitStock1 obj = new MaxProfitStock1();  
// price of the stock on the consecutive days  
int p1] = {70, 80, 230, 355, 10, 967, 517};  
int size = p1.length;// computing the size  of array


System.out.println("The cost of the stock on different days is: ");  


for(int i = 0; i< size; i++)  
{  
// displaying the price of the stock  
System.out.print(p1[i]+"");
}  


System.out.println("\n");  


//  calling the method
obj.stockBuyandSell(p1, size);  
}  
}  

Output:

Maximizing Profit in Stock Buy Sell in Java

Valley Peak Approach

In this approach, we need tohave an eye on the next larger element and subtract it from the current element. We do it as the difference keeps on growing unless we reach a minimum point. It is to be noted that, no extra spaces have been used. The time complexity of this approach remains to be O(size) only.

The subsequent Java program implements this approach.

public class MaxProfitStock2  
{  
// A method to compute the maximum profit using the price of the stock  
public int BuySellofstock(int pr[], int size)  
{  


// maxProfit adds up to the difference between the inline
// elements, only if they are lying in the uphill order  
int maxProfit = 0;  


// The loop begins from 1  
// as it is doing a comparison with the previous value  
for (int j = 1; j < size; j++)  
{  
if (pr[j] >pr[j - 1])  
{  
maxProfit = maxProfit + pr[j] - pr[j - 1];  
}  
}  
return maxProfit;  
}  


// main method  
public static void main(String argvs[])  
{  
// creation of an object of the class MaxProfitStock2  
MaxProfitStock2 obj = new MaxProfitStock2();  


// cost of stock on different days  
int pr[] = {60, 120, 240, 175, 80, 317, 407};  
int size = pr.length; // computing the size  


System.out.println("The price of the stock on multiple days is: ");  


for(int i1 = 0; i1 < size; i1++)  
{  
// displaying the price of the stock
System.out.print(pr[i1] + " ");  
}  


System.out.println("\n");  


// invoking the method BuySellofstock()  
obj.BuySellofstock(pr, size);  


int res  =obj.BuySellofstock(pr, size);  


System.out.print("The maximum profit made : ");  


System.out.print(res);  


}  
}

Output:

Maximizing Profit in Stock Buy Sell in Java

Example:

int pr[] = { 900, 895, 655, 540, 491, 321, 241, 181, 70, 15};

The price of a stock in this case is decreasing day by day. So, if a person buys a stock on a day, then any following day after the stock is bought shall have the price of the stock less than the purchased price. Hence, one will incur a loss.


Related Topics

Rectangular Numbers in Java

In this tutorial, we will understand the meaning of a rectangular number in Java with the aid of examples, illustrations, and implementations. It is one of the popular coding interview...

3 minutes read.

How to compare three dates in Java?

While using the date and the time in Java, we occasionally have to compare the dates. Java does not compare dates the same way it compares the two numbers. Therefore,...

6 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

How to Calculate Week Number From Current Date in Java?

The WeekFields class's weekOfMonth() method is utilized to return the field for access the week of a month based on this WeekFields. If the first day of the month is a...

3 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

Java 8 filters list

A stream with the components of this stream that match the given predicate is provided by the streaming filter (Predicate predicate). This process is step-by-step. Because these operations are always...

4 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

How to create array of objects in Java

Java is an object-oriented programming language therefore everything in Java is based on objects and classes. Array is a data structure that holds data of similar type and dynamically creates...

4 minutes read.

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

4 minutes read.

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.

Java Swings

Swing is a Java Foundation Class library and an extension to the Abstract Window Toolkit (AWT) (JFC).As compared to AWT, Swing has significantly better functionality, new components, increased component features,...

9 minutes read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Java Read File to String

There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications. There are different ways to deal with looking at a...

6 minutes read.

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

Advantages and Disadvantages of Strings in Java

What is a String? Java is an object-oriented, platform-independent, high-level, general-purpose, and interpreted programming language.Sun Microsystems is known as the founder of java in 1991; the Java programming language was developed...

4 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.