Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Javascript Program For Stock Buy Sell To Maximize Profit
Next article icon

Javascript Program For Stock Buy Sell To Maximize Profit

Last Updated : 30 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days. For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying on day 0, selling on day 3. Again buy on day 4 and sell on day 6. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.

Naive approach:

A simple approach is to try buying the stocks and selling them on every single day when profitable and keep updating the maximum profit so far.

Below is the implementation of the above approach:

JavaScript
// Javascript program to implement // the above approach  // Function to return the maximum profit // that can be made after buying and // selling the given stocks function maxProfit(price, start, end) {     // If the stocks can't be bought     if (end <= start)         return 0;      // Initialise the profit     let profit = 0;      // The day at which the stock     // must be bought     for (let i = start; i < end; i++) {         // The day at which the         // stock must be sold         for (let j = i + 1; j <= end; j++) {             // If buying the stock at ith day and             // selling it at jth day is profitable             if (price[j] > price[i]) {                 // Update the current profit                 let curr_profit = price[j] - price[i] +                     maxProfit(price,                         start, i - 1) +                     maxProfit(price,                         j + 1, end);                  // Update the maximum profit                  // so far                 profit = Math.max(profit,                     curr_profit);             }         }     }     return profit; }  // Driver code let price = [100, 180, 260, 310,     40, 535, 695]; let n = price.length; console.log(maxProfit(     price, 0, n - 1)); 

Output
865 

Complexity Analysis:

  • Time Complexity: O(N2)
  • Auxiliary Space: O(1)

Efficient approach:

If we are allowed to buy and sell only once, then we can use following algorithm. Maximum difference between two elements. Here we are allowed to buy and sell multiple times. 
Following is the algorithm for this problem.  

  1. Find the local minima and store it as starting index. If not exists, return.
  2. Find the local maxima. and store it as an ending index. If we reach the end, set the end as the ending index.
  3. Update the solution (Increment count of buy-sell pairs)
  4. Repeat the above steps if the end is not reached.
JavaScript
// JavaScript program to implement  // the above approach  // This function finds the buy sell // schedule for maximum profit function stockBuySell(price, n) {     // Prices must be given for at      // least two days     if (n == 1)         return;      // Traverse through given price array     let i = 0;     while (i < n - 1) {         // Find Local Minima         // Note that the limit is (n-2) as we          // are comparing present element to          // the next element         while ((i < n - 1) &&             (price[i + 1] <= price[i]))             i++;          // If we reached the end, break         // as no further solution possible         if (i == n - 1)             break;          // Store the index of minima         let buy = i++;          // Find Local Maxima         // Note that the limit is (n-1) as we          // are comparing to previous element         while ((i < n) &&             (price[i] >= price[i - 1]))             i++;          // Store the index of maxima         let sell = i - 1;          console.log(`Buy on day: ${buy}         Sell on day: ${sell}`);     } }  // Driver code // Stock prices on consecutive days let price = [100, 180, 260,     310, 40, 535, 695]; let n = price.length;  // Function call stockBuySell(price, n);  // This code is contributed by Potta Lokesh 

Output
Buy on day: 0         Sell on day: 3 Buy on day: 4         Sell on day: 6 

Complexity Analysis:

  • Time Complexity: The outer loop runs till I become n-1. The inner two loops increment value of I in every iteration. So overall time complexity is O(n)
  • Space Complexity: O(1) since using constant variables

Please refer complete article on Stock Buy Sell to Maximize Profit for more details!


Next Article
Javascript Program For Stock Buy Sell To Maximize Profit

K

kartik
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • DSA
  • Arrays
  • Microsoft
  • Amazon
  • Morgan Stanley
  • Oracle
  • Flipkart
  • Directi
  • Samsung
  • Goldman Sachs
  • Walmart
  • Paytm
  • Accolite
  • Hike
  • Sapient
  • SAP Labs
  • MakeMyTrip
  • Quikr
  • Ola Cabs
  • Pubmatic
  • Swiggy
Practice Tags :
  • Accolite
  • Amazon
  • Directi
  • Flipkart
  • Goldman Sachs
  • Hike
  • MakeMyTrip
  • Microsoft
  • Morgan Stanley
  • Ola Cabs
  • Oracle
  • Paytm
  • Pubmatic
  • Quikr
  • Samsung
  • SAP Labs
  • Sapient
  • Swiggy
  • Walmart
  • Arrays

Similar Reads

    Maximize profit in buying and selling stocks with Rest condition
    The price of a stock on each day is given in an array arr[] for N days, the task is to find the maximum profit that can be made by buying and selling the stocks in those days with conditions that the stock must be sold before buying again and stock cannot be bought on the next day of selling a stock
    15+ min read
    Maximize Profit by trading stocks based on given rate per day
    Given an array arr[] of N positive integers which denotes the cost of selling and buying a stock on each of the N days. The task is to find the maximum profit that can be earned by buying a stock on or selling all previously bought stocks on a particular day.Examples: Input: arr[] = {2, 3, 5} Output
    6 min read
    Maximize profit that can be earned by selling an item among N buyers
    Given an array arr[] of size N, the task is to find the price of the item such that the profit earned by selling the item among N buyers is maximum possible consisting of budgets of N buyers. An item can be sold to any buyer if the budget of the buyer is greater than or equal to the price of the ite
    10 min read
    Maximum profit by selling N items at two markets
    Given two arrays, A[] and B[] each of length N where A[i] and B[i] are the prices of the ith item when sold in market A and market B respectively. The task is to maximize the profile of selling all the N items, but there is a catch: if you went to market B then you can not return. For example, if yo
    12 min read
    Maximize the profit after selling the tickets | Set 2 (For elements in range [1, 10^6])
    Given an array, arr[] of size N where arr[i] represents the number of tickets, the ith seller has and a positive integer K. The price of a ticket is the number of tickets remaining with the ticket seller. They can sell a total of K tickets. Find the maximum amount they can earn by selling K tickets.
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences