20 decembrie 2023

50 DSA-Questions: Arrays #1, #2

#1. Two Sum
Given an array of integer nums and an integer target, return indices of the two numbers such that they add up to the target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i=0; i<nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                map.put(nums[i], new ArrayList<>()); // handle duplicate elements
            }
            map.get(nums[i]).add(i);
        }

        int [] indices = new int[2];
       
        for (int i=0; i<nums.length; i++) {
            int element = nums[i];
            map.get(element).remove(0);
            int key = target - element;
            if (map.containsKey(key) && !map.get(key).isEmpty()) {
                indices[0] = i;
                indices[1] = map.get(key).get(0);
                return indices; // assume exactly one solution
            }
        }

        return indices;
    }
}

#2. Best Time to Buy and Sell Stock
You are given an array of prices where prices[i] is the price of a given stock on an i-th day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
class Solution {
    public int maxProfit(int[] prices) {
        int[] min = new int[prices.length];
        min[0] = prices[0];
        for (int i = 1; i < prices.length; i++) {
            min[i] = prices[i] < min[i-1] ? prices[i] : min[i-1]; // min pana la momentul i, crescator
        }

        int[] max = new int[prices.length];
        max[prices.length - 1] = prices[prices.length - 1];
        for (int i = prices.length - 2; i > 0; i--) {
            max[i] = prices[i] > max[i+1] ? prices[i] : max[i+1]; // max pana la momentul i, descrescator
        }

        int maxProfit = 0;
        for (int i = 1; i < prices.length; i++) {
            int profit = max[i] - min[i];
            if (profit > maxProfit) {
                maxProfit = profit;
            }
        }

        return maxProfit;
    }
}

Niciun comentariu: