-
-
Save IrhaAli/d2ba33a642f6900e3f58e6b1064cd53f to your computer and use it in GitHub Desktop.
Given a list of stock prices for a given day, returns the maximum profit that could have been made by buying a stock at the given price and then selling the stock later on.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Javascript program to find Maximum | |
// difference between two elements | |
// such that larger element appears | |
// after the smaller number | |
/* The function assumes that there | |
are at least two elements in array. | |
The function returns a negative | |
value if the array is sorted in | |
decreasing order and returns 0 if | |
elements are equal */ | |
const stockMarket = function (arr) { | |
// Create a diff array of size n-1. | |
// The array will hold the difference | |
// of adjacent elements | |
let n = arr.length; | |
let diff = []; | |
for(let i = 0; i < n - 1; i++) { | |
diff.push(arr[i + 1] - arr[i]); | |
} | |
// Now find the maximum sum | |
// subarray in diff array | |
console.log(diff) | |
let max_diff = diff[0]; | |
for(let i = 1; i < n - 1; i++) | |
{ | |
if (diff[i - 1] > 0) | |
diff[i] += diff[i - 1]; | |
if (max_diff < diff[i]) | |
max_diff = diff[i]; | |
} | |
console.log(max_diff) | |
return max_diff; | |
} | |
// Test code | |
console.log(stockMarket([45, 24, 35, 31, 40, 38, 11])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment