Arrays January 13 ,2026

 

Stock Buy and Sell (Multiple Transactions)

Problem Statement

You are given an array prices[] where prices[i] represents the stock price on day i.

You can perform multiple buy and sell transactions with the following rules:

  • You must sell before buying again
  • You can hold only one stock at a time
  • You may buy and sell on the same day only once

Find the maximum profit achievable.

Example 1

Input

prices = [7, 1, 5, 3, 6, 4]

Output

7

Explanation

  • Buy at 1 → Sell at 5 (Profit = 4)
  • Buy at 3 → Sell at 6 (Profit = 3)
  • Total Profit = 7

Approaches Overview

ApproachTechniqueTimeSpace
Approach 1Brute ForceO(n²)O(1)
Approach 2Peak–Valley GreedyO(n)O(1)
Approach 3Sum of Positive DifferencesO(n)O(1)

Approach 1: Brute Force

Idea

Check all possible buy–sell pairs and accumulate profit whenever selling price is higher than buying price.

Algorithm

  1. Initialize profit = 0
  2. For each day i
  3. For each future day j > i
  4. If prices[j] > prices[i], add profit and move i forward
  5. Continue until array ends

Implementation

C

#include 

int main() {
    int prices[] = {7, 1, 5, 3, 6, 4};
    int n = 6, profit = 0;

    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (prices[j] > prices[i]) {
                profit += prices[j] - prices[i];
                i = j - 1;
                break;
            }
        }
    }

    printf("Maximum Profit: %d", profit);
    return 0;
}

C++

#include 
using namespace std;

int main() {
    int prices[] = {7, 1, 5, 3, 6, 4};
    int n = 6, profit = 0;

    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (prices[j] > prices[i]) {
                profit += prices[j] - prices[i];
                i = j - 1;
                break;
            }
        }
    }

    cout << "Maximum Profit: " << profit;
    return 0;
}

Java

public class StockBuySell {
    public static void main(String[] args) {
        int[] prices = {7, 1, 5, 3, 6, 4};
        int profit = 0;

        for (int i = 0; i < prices.length - 1; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                if (prices[j] > prices[i]) {
                    profit += prices[j] - prices[i];
                    i = j - 1;
                    break;
                }
            }
        }

        System.out.println("Maximum Profit: " + profit);
    }
}

Python

prices = [7, 1, 5, 3, 6, 4]
profit = 0
i = 0

while i < len(prices) - 1:
    j = i + 1
    while j < len(prices):
        if prices[j] > prices[i]:
            profit += prices[j] - prices[i]
            i = j - 1
            break
        j += 1
    i += 1

print("Maximum Profit:", profit)

JavaScript

let prices = [7, 1, 5, 3, 6, 4];
let profit = 0;

for (let i = 0; i < prices.length - 1; i++) {
    for (let j = i + 1; j < prices.length; j++) {
        if (prices[j] > prices[i]) {
            profit += prices[j] - prices[i];
            i = j - 1;
            break;
        }
    }
}

console.log("Maximum Profit:", profit);

Approach 2: Greedy Peak–Valley

Idea

  • Buy at local minima
  • Sell at local maxima
  • Add each transaction’s profit

Algorithm

  1. Traverse prices
  2. Find valley (buy)
  3. Find peak (sell)
  4. Add sell - buy to profit
  5. Repeat

Implementation

C

#include 

int main() {
    int prices[] = {7, 1, 5, 3, 6, 4};
    int n = 6, i = 0, profit = 0;

    while (i < n - 1) {
        while (i < n - 1 && prices[i] >= prices[i + 1])
            i++;

        int buy = prices[i];

        while (i < n - 1 && prices[i] <= prices[i + 1])
            i++;

        int sell = prices[i];
        profit += sell - buy;
    }

    printf("Maximum Profit: %d", profit);
    return 0;
}

C++

#include 
using namespace std;

int main() {
    int prices[] = {7, 1, 5, 3, 6, 4};
    int n = 6, i = 0, profit = 0;

    while (i < n - 1) {
        while (i < n - 1 && prices[i] >= prices[i + 1])
            i++;

        int buy = prices[i];

        while (i < n - 1 && prices[i] <= prices[i + 1])
            i++;

        int sell = prices[i];
        profit += sell - buy;
    }

    cout << "Maximum Profit: " << profit;
    return 0;
}

Java

public class StockBuySell {
    public static void main(String[] args) {
        int[] prices = {7, 1, 5, 3, 6, 4};
        int i = 0, profit = 0;

        while (i < prices.length - 1) {
            while (i < prices.length - 1 && prices[i] >= prices[i + 1])
                i++;

            int buy = prices[i];

            while (i < prices.length - 1 && prices[i] <= prices[i + 1])
                i++;

            int sell = prices[i];
            profit += sell - buy;
        }

        System.out.println("Maximum Profit: " + profit);
    }
}

Python

prices = [7, 1, 5, 3, 6, 4]
i = 0
profit = 0

while i < len(prices) - 1:
    while i < len(prices) - 1 and prices[i] >= prices[i + 1]:
        i += 1

    buy = prices[i]

    while i < len(prices) - 1 and prices[i] <= prices[i + 1]:
        i += 1

    sell = prices[i]
    profit += sell - buy

print("Maximum Profit:", profit)

JavaScript

let prices = [7, 1, 5, 3, 6, 4];
let i = 0, profit = 0;

while (i < prices.length - 1) {
    while (i < prices.length - 1 && prices[i] >= prices[i + 1])
        i++;

    let buy = prices[i];

    while (i < prices.length - 1 && prices[i] <= prices[i + 1])
        i++;

    let sell = prices[i];
    profit += sell - buy;
}

console.log("Maximum Profit:", profit);

Approach 3: Sum of Positive Differences (Best & Most Used)

Idea

Add profit whenever today’s price is greater than yesterday’s price.

Algorithm

  1. Initialize profit = 0
  2. Traverse from index 1
  3. If prices[i] > prices[i-1], add difference
  4. Return profit

Implementation

C

#include 

int main() {
    int prices[] = {7, 1, 5, 3, 6, 4};
    int n = 6, profit = 0;

    for (int i = 1; i < n; i++) {
        if (prices[i] > prices[i - 1])
            profit += prices[i] - prices[i - 1];
    }

    printf("Maximum Profit: %d", profit);
    return 0;
}

C++

#include 
using namespace std;

int main() {
    int prices[] = {7, 1, 5, 3, 6, 4};
    int profit = 0;

    for (int i = 1; i < 6; i++) {
        if (prices[i] > prices[i - 1])
            profit += prices[i] - prices[i - 1];
    }

    cout << "Maximum Profit: " << profit;
    return 0;
}

Java

public class StockBuySell {
    public static void main(String[] args) {
        int[] prices = {7, 1, 5, 3, 6, 4};
        int profit = 0;

        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i - 1])
                profit += prices[i] - prices[i - 1];
        }

        System.out.println("Maximum Profit: " + profit);
    }
}

Python

prices = [7, 1, 5, 3, 6, 4]
profit = 0

for i in range(1, len(prices)):
    if prices[i] > prices[i - 1]:
        profit += prices[i] - prices[i - 1]

print("Maximum Profit:", profit)

JavaScript

let prices = [7, 1, 5, 3, 6, 4];
let profit = 0;

for (let i = 1; i < prices.length; i++) {
    if (prices[i] > prices[i - 1]) {
        profit += prices[i] - prices[i - 1];
    }
}

console.log("Maximum Profit:", profit);

Final Summary

  • Brute Force → learning purpose only
  • Peak–Valley → conceptually clear
  • Positive Difference Greedy → best, simplest, interview-preferred

Next problem in the series-

Sort an Array of 0s, 1s, and 2s


 

Sanjiv
0

You must logged in to post comments.

Related Blogs

Find the S...
Arrays February 02 ,2026

Find the Second Smal...

Find the S...
Arrays January 01 ,2026

Find the Sum of All...

Find the M...
Arrays January 01 ,2026

Find the Maximum Ele...

Find the M...
Arrays January 01 ,2026

Find the Minimum Ele...

Count Even...
Arrays January 01 ,2026

Count Even and Odd N...

Search an...
Arrays January 01 ,2026

Search an Element in...

Copy One A...
Arrays January 01 ,2026

Copy One Array into...

Reverse an...
Arrays January 01 ,2026

Reverse an Array

Print Alte...
Arrays January 01 ,2026

Print Alternate Elem...

Find the L...
Arrays January 01 ,2026

Find the Length of a...

Check if a...
Arrays January 01 ,2026

Check if an Array is...

Find the F...
Arrays January 01 ,2026

Find the First Eleme...

Find the L...
Arrays January 01 ,2026

Find the Last Elemen...

Count the...
Arrays January 01 ,2026

Count the Number of...

Replace Al...
Arrays January 01 ,2026

Replace All Elements...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at E...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at O...

Find the A...
Arrays January 01 ,2026

Find the Average of...

Count the...
Arrays January 01 ,2026

Count the Number of...

Remove Dup...
Arrays January 01 ,2026

Remove Duplicate Ele...

Move All Z...
Arrays January 01 ,2026

Move All Zeros to th...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by K...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by O...

Check if T...
Arrays January 01 ,2026

Check if Two Arrays...

Merge Two...
Arrays January 01 ,2026

Merge Two Sorted Arr...

Find Missi...
Arrays January 01 ,2026

Find Missing Number...

Find Dupli...
Arrays January 01 ,2026

Find Duplicate Eleme...

Count Freq...
Arrays January 01 ,2026

Count Frequency of E...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All U...
Arrays January 01 ,2026

Find All Unique Elem...

Insert an...
Arrays January 01 ,2026

Insert an Element at...

Delete an...
Arrays January 01 ,2026

Delete an Element fr...

Find the I...
Arrays January 01 ,2026

Find the Index of an...

Find Union...
Arrays January 01 ,2026

Find Union of Two Ar...

Find Inter...
Arrays January 01 ,2026

Find Intersection of...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s...

Find the L...
Arrays January 01 ,2026

Find the Largest Sum...

Kadane’s A...
Arrays January 01 ,2026

Kadane’s Algorithm (...

Two Sum Pr...
Arrays January 01 ,2026

Two Sum Problem

Subarray w...
Arrays January 01 ,2026

Subarray with Given...

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Rearrange...
Arrays January 01 ,2026

Rearrange Array Alte...

Leaders in...
Arrays January 01 ,2026

Leaders in an Array

Equilibriu...
Arrays January 01 ,2026

Equilibrium Index of...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s,...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All P...
Arrays January 01 ,2026

Find All Pairs with...

Longest Co...
Arrays January 01 ,2026

Longest Consecutive...

Product of...
Arrays January 01 ,2026

Product of Array Exc...

Maximum Pr...
Arrays January 01 ,2026

Maximum Product Suba...

Find the F...
Arrays January 01 ,2026

Find the First Missi...

Count Inve...
Arrays January 01 ,2026

Count Inversions in...

Rearrange...
Arrays January 01 ,2026

Rearrange Array by S...

Check if A...
Arrays January 01 ,2026

Check if Array Can B...

Trapping R...
Arrays January 01 ,2026

Trapping Rain Water

Find Minim...
Arrays January 01 ,2026

Find Minimum in Rota...

Search in...
Arrays January 01 ,2026

Search in Rotated So...

Median of...
Arrays January 01 ,2026

Median of Two Sorted...

Merge Inte...
Arrays January 01 ,2026

Merge Intervals

Count Reve...
Arrays January 01 ,2026

Count Reverse Pairs

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Largest Re...
Arrays January 01 ,2026

Largest Rectangle in...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Rectangl...

Subarray S...
Arrays January 01 ,2026

Subarray Sum Equals...

Count Dist...
Arrays January 01 ,2026

Count Distinct Eleme...

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Maxim...

Find K Max...
Arrays January 01 ,2026

Find K Maximum Eleme...

Minimum Nu...
Arrays January 01 ,2026

Minimum Number of Ju...

Chocolate...
Arrays January 01 ,2026

Chocolate Distributi...

Find All T...
Arrays January 01 ,2026

Find All Triplets Wi...

Kth Smalle...
Arrays January 01 ,2026

Kth Smallest Element...

Maximum Le...
Arrays January 01 ,2026

Maximum Length Biton...

Find the S...
Arrays February 02 ,2026

Find the Second Larg...

Get In Touch

Kurki bazar Uttar Pradesh

+91-8808946970

techiefreak87@gmail.com