16. Best time to buy and sell shares

16. Best time to buy and sell shares


Problem link :- click here


//Best time to buy and sell shares 
package programs;

import java.util.*;

public class Array__16
{

	static int maxProfit(int arr[])
	{
		int i, min, profit;
		min = Integer.MAX_VALUE;
		profit = 0;
		for(i=0; i<arr.length; i++)
		{
			if(arr[i] < min)
				min = arr[i];
			if(arr[i]-min > profit)
				profit = arr[i]-min;
		}
		return profit;
	}
	
	public static void main(String[] args)
	{
		int i, n, ans;
		
		Scanner s = new Scanner(System.in);
		System.out .println("Enter the size of the array : ");
		n = s.nextInt();
		int array[] = new int[n];
		System.out.println("Enter the elements of the array\n");
		for(i=0; i<n; i++)
			array[i] = s.nextInt();
		
		System.out.println("Given array :");
		print_array(array, n);
		System.out.println("\n");
		
		ans = maxProfit(array);
		System.out.println("Maximum profit : " + ans);
	}

	static void print_array(int[] arr, int n)
	{
		for(int i=0; i<n; i++)
			System.out.print(arr[i] + " ");
	}
}

Time complexity :- O(n)
Space complexity :- O(1)


Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree