Created
          July 3, 2024 12:21 
        
      - 
      
- 
        Save basharkhan6/fa41e56eba2863dca73363ebd28e51b8 to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | // Problen 1 | |
| private static int[] twoSum(int[] arr, int target) { | |
| HashMap<Integer, Integer> visited = new HashMap<>(); // num -> idx | |
| for (int i=0; i< arr.length; i++) { | |
| int required = target-arr[i]; | |
| if (visited.containsKey(required)) { | |
| return new int[] {visited.get(required), i}; | |
| } | |
| visited.put(arr[i], i); | |
| } | |
| return new int[] {-1,-1}; | |
| } | |
| // Problem 2 | |
| private static int maxProfit(int[] arr) { | |
| int minIdx = minPrice(arr); | |
| int cost = arr[minIdx]; | |
| int max = 0; | |
| for (int i=minIdx+1; i<arr.length; i++) { | |
| int profit = arr[i] - cost; | |
| if (profit > max) { | |
| max = profit; | |
| } | |
| } | |
| return max; | |
| } | |
| private static int minPrice(int[] arr) { | |
| int minIdx = 0; | |
| for (int i=1; i<arr.length; i++) { | |
| if (arr[i] < arr[minIdx]) { | |
| minIdx = i; | |
| } | |
| } | |
| return minIdx; | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment