Buy and sell stocks | Part 2

Given an array of stock prices, find the maximum profit that can be earned by performing multiple non-overlapping transactions (buy and sell).
Example: {100, 80, 120, 130, 70, 60, 100, 125} Profit: 115


Question Asked in

Amazon


Please try solving this problem before jumping on the solution

Click to learn






Subscribe for more updates



Algorithm Visualization




Code Snippet

			
package com.ideserve.virendra.questions;

public class BuyAndSell {
	
	public static int maximumProfit2(int[] stockPrices) {
	    int totalProfit = 0;
	    for(int i=1; i<stockPrices.length; i++){
	        int  currentProfit = stockPrices[i]-stockPrices[i-1];
	        if(currentProfit > 0){
	        	totalProfit += currentProfit;
	        }
	    }
	    return totalProfit;
	}
	
	public static void main(String args[])
	{
		int[] p = {100, 80, 120, 130, 70, 60, 100, 125};
		System.out.println(maximumProfit2(p));
		
		
	}
}
		

Order of the Algorithm

Time Complexity is O(n)
Space Complexity is O(1)


Contribution

  • Sincere thanks from IDeserve community to Virendra Karappa for compiling current post.


    Virendra Karappa