Posts

Staircase Algorithm

def searchMatrix ( self , matrix : List[List[ int ]], target : int ) -> bool :         m = len (matrix)         if m > 0 :             n = len (matrix[ 0 ])         else :             n = 0         i = 0         j = n- 1         while i <= m- 1 and j >= 0 :             print (i,j)             if matrix[i][j] == target:                 return True             elif matrix[i][j] > target:                 print ( "greater" )                 j = j- 1             elif matrix[i][j] < target:                 print ( ...

Max Sum of Diagonal

n = int ( input ()) matrix = [ list ( map ( int , input ().split())) for _ in range (n)] main_diagonals = [ 0 ] * ( 2 * n - 1 ) anti_diagonals = [ 0 ] * ( 2 * n - 1 ) for i in range (n):     for j in range (n):         val = matrix[i][j]         main_diagonals[i - j + n - 1 ] += val         anti_diagonals[i + j] += val max_main = max (main_diagonals) max_anti = max (anti_diagonals) print ( max (max_main, max_anti))

Water Refelction Problem

import sys input = sys.stdin.readline n, m = map ( int , input ().split()) matrix = [] for _ in range (n):     row = list ( map ( int , input ().split()))     matrix.append(row) # Reverse vertically matrix.reverse() # Print result for row in matrix:     print ( ' ' .join( map ( str , row)))

best-time-to-buy-and-sell-stock

  class Solution :     def maxProfit ( self , prices : List[ int ]) -> int :         if not prices:             return 0         min_val = prices[ 0 ]         max_profit = 0         for price in prices:             if price < min_val:                 min_val = price             profit = price - min_val             if profit > max_profit:                 max_profit = profit         return  max_profit

4 sum Problem

  class Solution :   def fourSum ( self , nums : List[ int ], target : int ) -> List[List[ int ]]:         # sort the array         nums.sort()         res = []         n = len (nums)         for i in range (n):             # avoid duplicate             if i > 0 and nums[i] == nums[i- 1 ]:                 continue             for j in range (i+ 1 ,n):                 if j > i + 1 and nums[j] == nums[j- 1 ]:                     continue                                 left = j+ 1                 right = n- 1     ...

3 Sum Problem Leetcode

class Solution :     def threeSum ( self , nums : List[ int ]) -> List[List[ int ]]:         nums.sort()         new_list = []         for i in range ( len (nums)- 2 ):             if i > 0 and nums[i] == nums[i - 1 ]:                 continue             left = i+ 1             right = len (nums) - 1             while left < right:                 if nums[i] + nums[left] + nums[right] < 0 :                     left = left + 1                 elif nums[i] + nums[left] + nums[right] > 0 :                       right -= 1         ...