Skip to content

Commit

Permalink
leetcode
Browse files Browse the repository at this point in the history
  • Loading branch information
SamirPaulb committed Apr 4, 2022
1 parent 8f564ca commit e3348d1
Show file tree
Hide file tree
Showing 8 changed files with 70 additions and 3 deletions.
30 changes: 30 additions & 0 deletions 02_Dynamic-Programming/12. DP Using 1D Array/13. Stone Game.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# https://leetcode.com/problems/stone-game/
# https://youtu.be/uhgdXOlGYqE
'''
class Solution:
def stoneGame(self, piles: List[int]) -> bool:
# as sum(piles) is odd and Alice always choose first so there is always an way
that Alice will win
return True
'''

class Solution:
def stoneGame(self, piles: List[int]) -> bool:
dp = {}

def dfs(l, r):
if l > r: return 0

if (l, r) in dp: return dp[(l, r)]

even = True if (r - l) % 2 == 0 else False

left = piles[l] if even else 0
right = piles[r] if even else 0

dp[(l, r)] = max(left + dfs(l+1, r), right + dfs(l, r-1))

return dp[(l, r)]

return dfs(0, len(piles)-1) > sum(piles) // 2
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# https://leetcode.com/problems/stone-game-ii/

Empty file.

This file was deleted.

38 changes: 38 additions & 0 deletions 11_Binary-Search/05. Find Peak Element.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# https://leetcode.com/problems/find-peak-element/
# https://youtu.be/OINnBJTRrMU

class Solution:
def findPeakElement(self, nums: List[int]) -> int:
n = len(nums)
if n == 1: return 0

low = 0; high = n-1

while low <= high:

mid = low + (high - low) // 2
# Instead of writting mid = (low + high)//2 we should write mid = low + (high - low)//2 because of INTEGER OVERFLOW in the former case

if 0 < mid < n-1:
if nums[mid-1] < nums[mid] > nums[mid+1]:
return mid
elif nums[mid-1] > nums[mid]:
high = mid - 1
else:
low = mid + 1

else:
if mid == 0:
if nums[0] > nums[1]:
return 0
else:
return 1
if mid == n-1:
if nums[n-1] > nums[n-2]:
return n-1
else:
return n-2

# Time: O(n)
# Space: O(1)

0 comments on commit e3348d1

Please sign in to comment.