I am struggling to solve a hard problem (No. 1526) in LeetCode but only to fail since my codes are rejected again and again by 'time exceeded'.
Short Introduction to the No. 1526 Problem
The image below contains how I planned to solve the problem. Sorry for the bad resolution of it tho.
After I came up with this idea, I thought and still think it's a decent idea so I coded in two ways - recursive one and iterative one.
Recursive
target = [1, 2, 3, 2, 1]
score = 0
def minSubtract(target):
global score
if list(set(target)) == set([0]):
return
print(f"current arryay is {target}")
localMin = min(target)
score += localMin
newTargets = [ele - localMin for ele in target]
idx = 0
Arr = []
while idx < len(newTargets):
print(idx)
if newTargets[idx] != 0: # if nonzero element
subArr = [newTargets[idx]]
idx_ = idx + 1
while True:
if (idx_ >= len(newTargets) or (newTargets[idx_] == 0) ):
idx = idx_
Arr.append(subArr)
break
subArr.append(newTargets[idx_])
idx_ += 1
else:
idx += 1
print(f"subarrays are {Arr}")
for subArray in Arr:
minSubtract(subArray)
minSubtract(target)
score
Iterative
score = 0
stack = [target]
while stack:
curArr = stack.pop()
localMin = min(curArr)
if localMin == 0:
pass
score += localMin
SubtractedArr = [ele - localMin for ele in curArr]
idx = 0
Arrs = []
while idx < len(SubtractedArr):
if SubtractedArr[idx] != 0: # if nonzero element
subArr = [SubtractedArr[idx]]
idx_ = idx + 1
while True:
if (idx_ >= len(SubtractedArr) or (SubtractedArr[idx_] == 0) ):
idx = idx_
Arrs.append(subArr)
break
subArr.append(SubtractedArr[idx_])
idx_ += 1
else:
idx += 1
for newArr in Arrs:
stack.append(newArr)
score
However, they both pass 126/128 test cases but still have a runtime issue. I want to know what makes my code have so bad speed or if actually by idea itself sucks.

