Arrays
Coding Problems
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
. #leetcode
Time Complexity -O(n^2) - 45ms
1
2
3
4
5
6
7
8
9
10
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i < nums.length; i++) {
for(int j = i + 1; j < nums.length; j++) {
if(nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return new int[]{};
}
Time Complexity - O(n) - 2ms
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int composition_pair = target - nums[i];
if (map.containsKey(composition_pair)) {
return new int[]{ map.get(composition_pair), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution found");
}
You are given an array prices
where prices[i]
is the price of a given stock on the ith
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
.
Time Complexity - O(n^2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public int maxProfit(int[] prices) {
int maxProfit=0;
for (int i = 1; i<prices.length; i++) {
for (int j = 0; j < i; j++) {
int profit = prices[prices.length - 1-j] - prices[i - 1-j];
if (profit > maxProfit) {
maxProfit = profit;
System.out.println("Selling on Day " + j);
}
}
System.out.println("Buying on Day " + i);
}
return maxProfit;
}
This post is licensed under CC BY 4.0 by the author.