β Buy and Sell Stock(Contest)
Buy and Sell Stock easy Time Limit: 2 sec Memory Limit: 128000 kB
import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework
// don't change the name of this class
// you can add inner classes if needed
class Main {
public static void helper(int[] arr){
int maxProfit = Integer.MIN_VALUE;
int stockBought = arr[0];
for(int i=1; i< arr.length; i++){
if(stockBought > arr[i]){
stockBought = arr[i];
}else{
int currentProfit = arr[i] - stockBought;
maxProfit = Math.max(maxProfit, currentProfit);
}
}
if(maxProfit == Integer.MIN_VALUE){
System.out.println(0);
}else{
System.out.println(maxProfit);
}
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int []arr = new int[n];
for(int i=0; i<arr.length; i++){
arr[i] = sc.nextInt();
}
helper(arr);
}
}Last updated