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.
\
Solution:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
res = 0
lowest = float('inf')
for i in range(len(prices)):
if prices[i] < lowest:
lowest = prices[i]
elif prices[i] - lowest > res:
res = prices[i] - lowest
return res
# Or
class Solution:
def maxProfit(self, prices: List[int]) -> int:
l, r = 0, 1
res = 0
while r < len(prices):
if prices[l] < prices[r]:
res = max(res, prices[r] - prices[l])
else:
l = r
r += 1
return res
Given a string s, find the length of the longest substring without duplicate characters.
\
Solution:
We use a hash set to check if the character is present in the window or not. When we encounter a character at index r that is already present in the window, we shrink the window by incrementing the l pointer until the window no longer contains any duplicates. Also, we remove characters from the hash set that are excluded from the window as the l pointer moves. At each iteration, we update the result with the length of the current window
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
strSet = set()
res = 0
l = 0
for i in range(len(s)):
while strSet and s[i] in strSet:
strSet.remove(s[l])
l += 1
strSet.add(s[i])
res = max(res, len(strSet))
return res
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.
Return the length of the longest substring containing the same letter you can get after performing the above operations.
\
Solution: