· 1 min read
Blind 75 - Best Time To Buy And Sell Stock
Make sure the left pointer is always the lowest yet. Keep checking the difference between left and right. And return max.
Learning From
Asked at
Video
https://youtu.be/7KHKFqLPMbsProblem and Constraints
Given an array of stock prices. What’s the maximum profile that one can get?
All Approaches and Explanations in English
O(n) time complexity. O(1) space complexity
Make sure the left pointer is always the lowest yet. Keep checking the difference between left and right. And return max.
Code, if any
class Solution {
public int maxProfit(int[] prices) {
int left = 0;
int right = 1;
int maxYet = 0;
while(right < prices.length){
int leftItem = prices[left];
int rightItem = prices[right];
if(rightItem < leftItem){
left = right;
right = right+1;
continue;
}
maxYet = Math.max(maxYet, rightItem - leftItem);
right++;
}
return maxYet;
}
}