[Solved] Stock Picker Have the function StockPicker

Have the function StockPicker(arr) take the array of numbers stored in arr which will contain integers that represent the amount in dollars that a single stock is worth, and return the maximum profit that could have been made by buying stock on day x and selling stock on day y where y > x. For example: if arr is [44, 30, 24, 32, 35, 30, 40, 38, 15] then your program should return 16 because at index 2 the stock was worth $24 and at index 6 the stock was then worth $40, so if you bought the stock at 24 and sold it at 40, you would have made a profit of $16, which is the maximum profit that could have been made with this list of stock prices.

If there is not profit that could have been made with the stock prices, then your program should return -1. For example: arr is [10, 9, 8, 2] then your program should return -1.

Once your function is working, take the final output string and concatenate it with your ChallengeToken, and then replace every third character with an X.

Your ChallengeToken: wfmn8oc54a2

Examples

Input: new int[] {10,12,4,5,9}

Output: 5

Final Output: 5wXmnXocX4aX

Input: new int[] {14,20,4,12,5,11}

Output: 8

Final Output: 8wXmnXocX4aX

Solution

import java.util.*; 
import java.io.*;

class Main {
  public static void main (String[] args) {  
    // keep this function call here     
    Scanner s = new Scanner(System.in);
    System.out.print(StockPicker(s.nextLine()));
  }

  public static String StockPicker(String str) { 
    String[] arr = str.split(",");
    int[] arr2 = new int[arr.length];
    for(int i = 0; i < arr.length; i++){
      arr2[i] = Integer.parseInt(arr[i]);
    }
    int maxProfit = -1;
    for(int i = 0; i < arr2.length; i++){
      for(int j = i+1; j < arr2.length; j++){
        if(arr2[j] - arr2[i] > maxProfit){
          maxProfit = arr2[j] - arr2[i];
          // sauravhathi
        }
      }
    }
    if (maxProfit == -1) {
      return "-1";
    }
    String finalOutput = maxProfit + "wfmn8oc54a2";
    for (int i = 0; i < finalOutput.length(); i += 3) {
      finalOutput = finalOutput.substring(0, i+2) + "X" + finalOutput.substring(i+3);
    }
    return finalOutput;
  }  
}

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

📌 Nodejs and Android 😎
📌 Java

Articles: 444

Leave a Reply

Your email address will not be published. Required fields are marked *