Skip to content

Commit

Permalink
Best Time to Buy and Sell Stock
Browse files Browse the repository at this point in the history
  • Loading branch information
dksifoua committed Jan 24, 2024
1 parent e56e88e commit 68b9de1
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 7 deletions.
15 changes: 8 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,11 @@ int sum(int[] A, int n) {

## Solutions

| ID | Difficulty | Problem | Topics | Solution Link |
|------|------------|------------------|----------------------------|---------------------------------------------|
| 0001 | Easy | Two Sum | Array, HashMap | [solution](./docs/0001-Two-Sum.md) |
| 0002 | Medium | Add Two numbers | LinkedList, Recursion | |
| 0125 | Easy | Valid Palindrome | String, Two Pointers | [solution](./docs/0125-Valid-Palindrome.md) |
| 0242 | Easy | Valid Anagram | String, HashTable | [solution](./docs/0242-Valid-Anagram.md) |
| 0169 | Easy | Majority Element | Array, HashTable, Counting | [solution](./docs/0169-Majority-Element.md) |
| ID | Difficulty | Problem | Topics | Solution Link |
|------|------------|---------------------------------|----------------------------|-----------------------------------------------------------|
| 0001 | Easy | Two Sum | Array, HashMap | [solution](./docs/0001-Two-Sum.md) |
| 0002 | Medium | Add Two numbers | LinkedList, Recursion | |
| 0121 | Easy | Best Time to Buy and Sell Stock | Array | [solution](/docs/0121-Best-Time-to-Buy-and-Sell-Stock.md) |
| 0125 | Easy | Valid Palindrome | String, Two Pointers | [solution](./docs/0125-Valid-Palindrome.md) |
| 0169 | Easy | Majority Element | Array, HashTable, Counting | [solution](./docs/0169-Majority-Element.md) |
| 0242 | Easy | Valid Anagram | String, HashTable | [solution](./docs/0242-Valid-Anagram.md) |
51 changes: 51 additions & 0 deletions docs/0121-Best-Time-to-Buy-and-Sell-Stock.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/)

## Intuition

The basic idea is to find the lowest price to buy the stock (buy) and then find the highest price to sell the stock
after that day (sell). The goal is to maximize the difference between the selling and buying prices, which represents
the profit. It's important to note that we must buy before we sell, and we can only perform one buy and one sell
operation.

## Approach

1. Initialization:

- Start with a `maxP` variable set to 0, representing the maximum profit.
- Initialize `buy` and `sell` variables with the price on the first day.

2. Iterating Through Prices:

- Loop through the array of prices starting from the second day.
- If the current price is less than the current buy price, update buy and sell to this lower price. This step
ensures we're considering the lowest price so far to buy the stock.
- If the current price is higher than the current sell price, update sell to this price. This step looks for a
higher selling price after the buying day.
- After each iteration, update `maxP` by calculating the profit (`sell - buy) and comparing it with the current `
maxP`. The profit is only updated if it's greater than the previous `maxP`.

3. Return the Maximum Profit:

After iterating through all the prices, `maxP` will hold the maximum profit achievable.

## Complexity

- **Time complexity: O(N)** where N is the number of days (the length of the `prices array). This is because it requires
a single pass through the array, checking each price once.
- **Space complexity: O(1)** since only a constant amount of extra space is used (for the variables `maxP`, `buy`,
and `sell`).

## Code

[Link](/src/main/java/io/dksifoua/leetcode/majorityelement/Solution.java)

## Summary

This approach is optimal for several reasons:

- **Efficiency:** It efficiently finds the maximum profit with a single pass through the stock prices, avoiding the need
for nested loops which would increase the time complexity.
- **Simplicity:** The logic is straightforward and easy to understand, focusing on updating the buy and sell prices
based on the conditions that define the maximum profit.
- **Practicality:** The solution is practical and aligns well with real-world scenarios, where we want to buy low and
sell high.
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package io.dksifoua.leetcode.besttimetobuyandsellstock;

public class Solution {

public int maxProfit(int[] prices) {
if (prices.length == 0) return 0;

int maxP = 0;
int buy = prices[0], sell = prices[0];
for (int i = 1; i < prices.length; i++) {
if (prices[i] < buy) {
buy = prices[i];
sell = prices[i];
}
if (prices[i] > sell) {
sell = prices[i];
}

maxP = Math.max(maxP, Math.max(sell - buy, 0));
}

return maxP;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package io.dksifoua.leetcode.besttimetobuyandsellstock;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class SolutionTest {

private final Solution solution = new Solution();

@Test
void test1() {
Assertions.assertEquals(5, solution.maxProfit(new int[] { 7, 1, 5, 3, 6, 4 }));
}

@Test
void test2() {
Assertions.assertEquals(0, solution.maxProfit(new int[] { 7, 6, 4, 3, 1 }));
}
}

0 comments on commit 68b9de1

Please sign in to comment.