31 lines
985 B
Markdown
31 lines
985 B
Markdown
# Lessons Learned from LeetCode
|
|
## Slicing
|
|
- How to use slicing for shifting elements
|
|
|
|
```
|
|
my_list = [1, 2, 3, 4, 5]
|
|
|
|
# Shift list to the right using positive slicing
|
|
shifted_positive = my_list[-2:] + my_list[:-2]
|
|
print(shifted_positive) # Output: [4, 5, 1, 2, 3]
|
|
|
|
# Shift list to the left using negative slicing
|
|
shifted_negative = my_list[2:] + my_list[:2]
|
|
print(shifted_negative) # Output: [3, 4, 5, 1, 2]
|
|
|
|
```
|
|
## Dynamically Updating a value in a Single Pass
|
|
|
|
```
|
|
# Code with faster Implementation
|
|
min_price = prices[0] # Track the minimum price seen so far
|
|
max_profit = 0 # Track the maximum profit
|
|
|
|
for price in prices:
|
|
# print(f'price is {price}')
|
|
# print(f'MinPrice: {min_price} or {price}')
|
|
# print(f'MaxProfit: {max_profit} or [{price} - {min_price} = {max(max_profit, price - min_price)}]')
|
|
min_price = min(min_price, price) # Update the minimum price
|
|
max_profit = max(max_profit, price - min_price) # Update the maximum profit
|
|
return max_profit
|
|
``` |