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. Max number of entries 10^5, see if you need to use long int or other data type based on this.

Intuition

  • initialization_phase two variables, Max_profit and min_price with values 0 and first value of array
  • maintaince_phase min price is minimum of current price and min price
  • Max is Max_profit and difference of current price and min price
  • termination_phase return the Max profit

Code

def max_profit(prices):
    if not prices or len(prices) == 1:
        return 0
    
    max_profit = 0
    min_price = prices[0]
    
    for price in prices[1:]:
        min_price = min(min_price, price)
        max_profit = max(max_profit, price - min_price)
    
    return max_profit

HEPL assignment ✅

function ArrayChallenge(arr) {
 
  
 
// code goes here
 
/**
 
* Story:
 
* Difference between consecutive days is required,
 
* Q. can cumulative sum help here?
 
* How to find the max profit after finding the cumulative sum?
 
* Difference of every day will need to be calculated.
 
* If it has to be calcuated for only one stock, we can find the min
 
* and substract?
 
* Single pass? Not an issue, Math.min for min and Math.max for max after the first
 
* pass assign the values.
 
* Edge cases?
 
* - If arr is null return -1, assign result as -1 and take max or this
 
* - If arr is empty again above, do if !arr || arr.length === 0 return res (-1)
 
*
 
*/
 
if (!arr || (arr.length === 0)) {
 
return -1
 
}
 
  
 
// above won't work, what if min value came after max value?
 
// brute force nested for loop can help with same by a check of greater than
 
// we need min till now and not overall min
 
let minTillNow = Number.MAX_VALUE;
 
let maxProfit = Number.MIN_VALUE;
 
for (let i = 0; i < arr.length; i++) {
 
let cur = arr[i];
 
if (cur < minTillNow) {
 
minTillNow = cur;
 
}
 
let curProfit = cur - minTillNow;
 
if (curProfit > maxProfit) {
 
maxProfit = curProfit;
 
}
 
}
 
return maxProfit+":"+ "xfwgout137".split('').reverse().join('');
 
  
 
}
 
// keep this function call here
 
console.log(ArrayChallenge(readline()));