Skip to main content
Code Review

Return to Question

Commonmark migration
Source Link

##Problem

Problem

Given an array and a number \$t\$, write a function that determines if there exists a contiguous sub-array whose sum is \$t\$.

Source (Note that the URL may not link to the exact problem as it's from a quiz site, and questions seem to be randomly generated).

I was able to come up with a \$O(n^2)\$ solution, and further thinking hasn't improved upon it:

def substring_sum(lst, target):
 sums = []
 for val in lst:
 if val == target:
 return True
 for idx, _ in enumerate(sums):
 sums[idx] += val
 if sums[idx] == target:
 return True
 sums.append(val)
 return False

##Problem

Given an array and a number \$t\$, write a function that determines if there exists a contiguous sub-array whose sum is \$t\$.

Source (Note that the URL may not link to the exact problem as it's from a quiz site, and questions seem to be randomly generated).

I was able to come up with a \$O(n^2)\$ solution, and further thinking hasn't improved upon it:

def substring_sum(lst, target):
 sums = []
 for val in lst:
 if val == target:
 return True
 for idx, _ in enumerate(sums):
 sums[idx] += val
 if sums[idx] == target:
 return True
 sums.append(val)
 return False

Problem

Given an array and a number \$t\$, write a function that determines if there exists a contiguous sub-array whose sum is \$t\$.

Source (Note that the URL may not link to the exact problem as it's from a quiz site, and questions seem to be randomly generated).

I was able to come up with a \$O(n^2)\$ solution, and further thinking hasn't improved upon it:

def substring_sum(lst, target):
 sums = []
 for val in lst:
 if val == target:
 return True
 for idx, _ in enumerate(sums):
 sums[idx] += val
 if sums[idx] == target:
 return True
 sums.append(val)
 return False
edited title
Link
IEatBagels
  • 12.7k
  • 3
  • 48
  • 99

(Brilliant.org) Arrays Intermediate 3: Contiguous Knapsack

Source Link
Tobi Alafin
  • 1.8k
  • 1
  • 15
  • 31

(Brilliant) Arrays Intermediate 3: Contiguous Knapsack

##Problem

Given an array and a number \$t\$, write a function that determines if there exists a contiguous sub-array whose sum is \$t\$.

Source (Note that the URL may not link to the exact problem as it's from a quiz site, and questions seem to be randomly generated).

I was able to come up with a \$O(n^2)\$ solution, and further thinking hasn't improved upon it:

def substring_sum(lst, target):
 sums = []
 for val in lst:
 if val == target:
 return True
 for idx, _ in enumerate(sums):
 sums[idx] += val
 if sums[idx] == target:
 return True
 sums.append(val)
 return False
lang-py

AltStyle によって変換されたページ (->オリジナル) /