Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update BestTimeToBuyAndSellStock.java #238

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 24 additions & 23 deletions company/amazon/AddTwoNumbers.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,35 +15,36 @@
*/
public class AddTwoNumbers {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode current1 = l1;
ListNode current2 = l2;
ListNode dummyHead = new ListNode(0); // Dummy node to simplify the result list creation
ListNode current = dummyHead; // Pointer for traversing the result list
int carry = 0; // Variable to track the carry

ListNode head = new ListNode(0);
ListNode currentHead = head;

int sum = 0;

while(current1 != null || current2 != null) {
sum /= 10;
// Traverse both lists until both are null and there's no carry left
while (l1 != null || l2 != null || carry != 0) {
int sum = carry; // Start with the carry from the previous addition

if(current1 != null) {
sum += current1.val;
current1 = current1.next;
// Add value from the first list if available
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}

if(current2 != null) {
sum += current2.val;
current2 = current2.next;
// Add value from the second list if available
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}

currentHead.next = new ListNode(sum % 10);
currentHead = currentHead.next;
}

if(sum / 10 == 1) {
currentHead.next = new ListNode(1);
// Compute the new carry (either 1 or 0) for the next iteration
carry = sum / 10;
// Create a new node with the digit and attach it to the result list
current.next = new ListNode(sum % 10);
current = current.next;
}

return head.next;
// Return the result list, skipping the dummy head
return dummyHead.next;
}
}

44 changes: 17 additions & 27 deletions leetcode/array/BestTimeToBuyAndSellStock.java
Original file line number Diff line number Diff line change
@@ -1,36 +1,26 @@
// Say you have an array for which the ith element is the price of a given stock on day i.

// If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

// Example 1:
// Input: [7, 1, 5, 3, 6, 4]
// Output: 5

// max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
// Example 2:
// Input: [7, 6, 4, 3, 1]
// Output: 0

// In this case, no transaction is done, i.e. max profit = 0.

public class BestTimeToBuyAndSellStock {

public int maxProfit(int[] prices) {
//Kadane's algorithm
if(prices.length == 0) {
// Return 0 if there are no prices or only one price (no transaction possible)
if (prices == null || prices.length < 2) {
return 0;
}

int min = prices[0];
int max = 0;

for(int i = 1; i < prices.length; i++) {
if(prices[i] > min) {
max = Math.max(max, prices[i] - min);
} else {
min = prices[i];
}
int minPrice = prices[0]; // Initialize with the first price
int maxProfit = 0; // No profit made at the start

// Iterate over the prices starting from the second day
for (int i = 1; i < prices.length; i++) {
// Calculate potential profit by selling at the current price and buying at the minimum price
int potentialProfit = prices[i] - minPrice;

// Update the maximum profit if the potential profit is higher
maxProfit = Math.max(maxProfit, potentialProfit);

// Update the minimum price if the current price is lower
minPrice = Math.min(minPrice, prices[i]);
}

return max;
return maxProfit; // Return the maximum profit found
}
}
38 changes: 29 additions & 9 deletions leetcode/array/ContainsDuplicatesII.java
Original file line number Diff line number Diff line change
@@ -1,18 +1,38 @@
//Given an array of integers and an integer k, find out whether there are two distinct indices i and
//j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

import java.util.Map;
import java.util.HashMap;

class ContainsDuplicatesII {
/**
* Check if there are duplicates within a given distance k.
*
* @param nums the array of integers
* @param k the maximum distance
* @return true if duplicates exist within distance k, false otherwise
*/
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++) {
int current = nums[i];
if(map.containsKey(current) && i - map.get(current) <= k) {
return true;
} else {
map.put(current, i);
// Return false if nums is null or has fewer than 2 elements
if (nums == null || nums.length < 2 || k < 0) {
return false;
}

// Use a Map to store the most recent index of each value
Map<Integer, Integer> indexMap = new HashMap<>();

for (int i = 0; i < nums.length; i++) {
int currentValue = nums[i];

// Check if the current value has been seen before and within the allowed distance
if (indexMap.containsKey(currentValue) && (i - indexMap.get(currentValue) <= k)) {
return true; // Found a nearby duplicate
}

// Update the index of the current value
indexMap.put(currentValue, i);
}
return false;

return false; // No nearby duplicates found
}
}