Buy Or Sale Stocks with Alo
After Learn Linear Search with Alo , now it's time to solve one of the most popular interview questions.
Exploring BuyOrSaleStocks with Linear Search Algorithm
Meet Alo, our adventurous programmer, as he embarks on a
journey to unravel the mysteries of the BuyOrSaleStocks algorithm implemented
in your favourite language. 🚀 Alo is here to guide us through the code,
ask questions that might pop up in the minds of new programmers, and provide
solutions along the way.
The main limitation of linear search is its time complexity. Since it has to search each element one by one sequentially, its time complexity is O(n) where n is the number of elements. This means as the data set size increases, the search time increases linearly.
How long it takes for Linear depends on how many items there
are.
Introducing Alo
If you're all about giving instructions and getting things done, you might just have a friend in your life like Alo.
🚀 Meet Alo: The MIND-BLOWING Instruction-Based
Genius! No Senses, No Thoughts, But Can Master Algorithmic Concepts? 🤯
He not only teaches you but also provides challenges to make your day happier.😃
Alo's Quest
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.
Example 1:
Input: prices = [7, 2, 3, 4, 5, 6, 7, 8]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day
5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not
allowed because you must buy before you sell.
Solutions
1. See how Alo can create a solution.
Alo not only solves the problem but also demonstrates how to find the minimum and maximum numbers from a list of numbers. How to call method?
// Buy Or Sale Stocks
namespace BuyOrSaleStocks
{
public class BuyOrSaleStocks
{
private int BuyOrSaleStocksProfit(int[] prices)
{
int today = prices[0];
int MaxProfit = 0;
for (int i = 1; i < prices.Length; i++)
{
today= Math.Min(today, prices[i]);
MaxProfit = Math.Max(MaxProfit, prices[i]-today);
Console.WriteLine($"max profit in this Buy at {today} > Sale at {prices[i]} transaction profit is {MaxProfit}");
}
return MaxProfit;
}
private int BuyOrSaleStockLinq(int[] prices)
{
return prices.Skip(1).Aggregate((maxProfit: 0, today: prices[0]), (result, price) =>
{
result.today = Math.Min(result.today, price);
result.maxProfit = Math.Max(result.maxProfit, price - result.today);
Console.WriteLine($"Max profit in this Buy at {result.today} > Sale at {price} transaction profit is {result.maxProfit}");
return result;
}).maxProfit;
}
public static void Main(string[] args)
{
Console.WriteLine("Best time to Buy and Sale Stock");
int[] prices = { 7, 2, 3, 4, 5, 6, 7, 8 };
BuyOrSaleStocks buyOrSaleStocks = new BuyOrSaleStocks();
int profit = buyOrSaleStocks.BuyOrSaleStocksProfit(prices);
int ProfitLinq = buyOrSaleStocks.BuyOrSaleStockLinq(prices);
Console.WriteLine($"Maximum profit from this trends is :{profit}");
Console.WriteLine($"Maximum profit from this trends by linq is :{ProfitLinq}");
Console.ReadLine();
}
}
}
// Buy Or Sale Stocks
class Main {
private int buyOrSaleStocksProfit(int[] prices) {
int today = prices[0];
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
today = Math.min(today, prices[i]);
maxProfit = Math.max(maxProfit, prices[i] - today);
System.out.println("max profit in this Buy at" + today + " > Sale at" + prices[i] +
" transaction profit is " + maxProfit);
}
return maxProfit;
}
public static void main(String[] args) {
System.out.println("Best time to Buy and Sale Stock ");
int[] prices = { 7, 2, 3, 4, 5, 6, 7, 8 };
Main main = new Main();
int profit = main.buyOrSaleStocksProfit(prices);
System.out.println("Maximum profit from this trend is: " + profit);
}
}
// Buy Or Sale Stocks
class Main {
buyOrSaleStocksProfit(prices) {
let today = prices[0];
let maxProfit = 0;
for (let i = 1; i < prices.length; i++) {
today = Math.min(today, prices[i]);
maxProfit = Math.max(maxProfit, prices[i] - today);
console.log(
"max profit in this Buy at " +
today +
" > Sale at " +
prices[i] +
" transaction profit is " +
maxProfit
);
}
return maxProfit;
}
static main() {
console.log("Best time to Buy and Sale Stock ");
const prices = [7, 2, 3, 4, 5, 6, 7, 8];
const main = new Main();
const profit = main.buyOrSaleStocksProfit(prices);
console.log("Maximum profit from this trend is: " + profit);
}
}
// Run the main method
Main.main();
# Buy Or Sale Stocks
class Main:
def buy_or_sale_stocks_profit(self, prices):
today = prices[0]
max_profit = 0
for i in range(1, len(prices)):
today = min(today, prices[i])
max_profit = max(max_profit, prices[i] - today)
print(
f"max profit in this Buy at {today} > Sale at {prices[i]} transaction profit is {max_profit}"
)
return max_profit
@staticmethod
def main():
print("Best time to Buy and Sale Stock ")
prices = [7, 2, 3, 4, 5, 6, 7, 8]
main_instance = Main()
profit = main_instance.buy_or_sale_stocks_profit(prices)
print("Maximum profit from this trend is:", profit)
# Run the main method
Main.main()
// Buy Or Sale Stocks
struct Main;
impl Main {
fn buy_or_sale_stocks_profit(&self, prices: Vec<i32>) -> i32 {
let mut today = prices[0];
let mut max_profit = 0;
for &price in &prices[1..] {
today = today.min(price);
max_profit = max_profit.max(price - today);
println!(
"max profit Buy at {} > Sale at {} transaction profit is {}",
today, price, max_profit
);
}
max_profit
}
fn main() {
println!("Best time to Buy and Sale Stock ");
let prices = vec![7, 2, 3, 4, 5, 6, 7, 8];
let main_instance = Main;
let profit = main_instance.buy_or_sale_stocks_profit(prices);
println!("Maximum profit from this trend is: {}", profit);
}
}
fn main() {
Main::main();
}
Alo's Questions and Answers
Initializing the Adventure
Alo: Hey there! What's this
"BuyOrSaleStocks" all about? 🧐
Guide: Alo, we're exploring an algorithm to find the
best time to buy and sell stocks, a common challenge in trading. Check out the BuyOrSaleStocksProfit
method; that's where the magic happens.
Here, Alo showcases how to create a method and call it
within the main method.
Setting the Stage
Alo: Okay, I see the today and MaxProfit
variables. What's their role? 🤔
Guide: Good eye, Alo! today tracks the minimum
stock price encountered so far, and MaxProfit keeps the maximum profit
calculated during the traversal.
Alo creates memory points with two variables.
The Loop Unveiled
Alo: Ah, the loop! What's it doing? 🔄
Guide: The loop iterates through the stock prices,
updating today and MaxProfit along the way. today ensures
we consider the lowest stock price, and MaxProfit calculates the
potential profit if we sell at the current price.
In this loop, the main intention is to find the minimum and
maximum values from the list while skipping the 0th element.
Crunching the Numbers
Alo: How does the algorithm calculate the maximum
profit? 📈
Guide: Excellent question! It calculates the profit
by subtracting the minimum encountered price (today) from the current
price. The loop ensures we explore different buying and selling scenarios.
Stepping into the Main Adventure
Alo: Moving on to the Main method. What's
happening there? 🚦
Guide: In the Main method, we create an
instance of BuyOrSaleStocks, feed it some stock prices, and display the
maximum profit calculated by our algorithm.
Wrapping up the Adventure
Alo: So, what's the takeaway? 🏁
Guide: The algorithm efficiently finds the best time
to buy and sell stocks with a linear search. It's simple yet powerful, making
it a great starting point for understanding stock trading algorithms.
Dry Run
Lets check Alo's code with dry run
A dry run is a valuable practice to ensure that the program works as expected before executing it on a computer.
|
Day
(i) |
Stock
Price |
Today's
Min Price |
Max
Profit |
|
1 |
7 |
7 |
0 |
|
2 |
2 |
2 |
0 |
|
3 |
3 |
2 |
1 |
|
4 |
4 |
2 |
2 |
|
5 |
5 |
2 |
3 |
|
6 |
6 |
2 |
4 |
|
7 |
7 |
2 |
5 |
|
8 |
8 |
2 |
6 |
Explanation
- Day
(i): The current day in our stock price array.
- Stock
Price: The stock price on the current day.
- Today's
Min Price: The minimum stock price encountered until the current day.
- Max
Profit: The maximum profit that can be obtained by selling at the
current day's price.
Step-by-Step Walkthrough
- Day
1 (i=1): Buy at $7, set today to $7, and MaxProfit
remains 0.
- Day
2 (i=2): Buy at $2 (lower than today), update today to
$2, and MaxProfit remains 0.
- Day
3 (i=3): Sell at $3, update MaxProfit to $1 (3 - 2).
- Day
4 (i=4): Sell at $4, update MaxProfit to $2 (4 - 2).
- Day
5 (i=5): Sell at $5, update MaxProfit to $3 (5 - 2).
- Day
6 (i=6): Sell at $6, update MaxProfit to $4 (6 - 2).
- Day
7 (i=7): Sell at $7, update MaxProfit to $5 (7 - 2).
- Day
8 (i=8): Sell at $8, update MaxProfit to $6 (8 - 2).
Run Code on Replit with Your Favorite Language
Create similar example from you imagination and try on Replit online compiler .If you're looking to implement algorithm and want to try it out in your preferred programming language, you're in luck! You can easily run the above code on the online platform Replit.
3. Javascript | Buy Or Sale Stocks
4. Python | Buy Or Sale Stocks
LeetCode Problems on Linear Search
1. Two Sum
Problem : Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to 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.
Example 1:
Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
LeetCode Problem Link: Two Sum
2. Best Time to Buy and Sell Stock - Done
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.
Example 1:
Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
3. Contains Duplicate
Problem Description: Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
Example 1:
Input: nums = [1,2,3,1] Output: true
LeetCode Problem Link: Contains Duplicate - LeetCode
4. Search Insert Position
Problem Description: Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operation.
Example 1:
Input: nums = [1,2,3,4] Output: [24,12,8,6]
LeetCode Problem Link: Product of Array Except Self - LeetCode
All of your improvement comments will contribute to shaping
ALO better. Additionally, please include your own examples in the comments.
Feel free to create a program on Replit and share the link in the comments for
collaborative contribution.
