Easy
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.
Example 2:
Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no transactions are done and the max profit = 0.
Solution:
class Solution:
def maxProfit(self, prices: List[int]) -> int:
l,r=0,1 #left , right pointer
maxP=0
while r < len(prices):
if prices[l]< prices[r]:
profit = prices[r]-prices[l]
maxP = max(maxP, profit)
if prices[l]> prices[r]:
l = r
r+=1
return maxP
Medium
Given a string s, find the length of the longest without duplicate characters.
Example 1:
Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Note that"bca"and"cab"are also correct answers.
Example 2:
Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Solution:
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
l =0 # left , right pointer
a = set()
res =0
# enumerate gives us the index 'r' AND the character 'c'
for r,c in enumerate(s):
while c in a: # in s=pwwtfg remove form left(l) till c value is removed from set a.
a.remove(s[l])
l+=1
a.add(c)
res= max(res, r-l+1)
return res
Easy
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
Example 1:
Input: nums = [1,2,3,1], k = 3 Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1 Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2 Output: false
Constraints:
1 <= nums.length <= 105-109 <= nums[i] <= 1090 <= k <= 105
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
w=set()
l=0
for r, c in enumerate(nums):
if r-l > k:
w.remove(nums[l])
l+=1
if c in w:
return True
w.add(c)
return False
Check out my Cyber Security Youtube channel: zodiac
Comments
Post a Comment