summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormo khan <mo@mokhan.ca>2021-11-07 16:02:42 -0700
committermo khan <mo@mokhan.ca>2021-11-07 16:02:42 -0700
commit51c05013fff2c817ffb4a8649eed8ee2836e95b1 (patch)
treef2c62e9fb496a61ca205e914c9067af3289d6961
parent1af2c5f253f426327f61c819ea576b6c70adc940 (diff)
answer a few more questions
-rw-r--r--0x01/README.md51
-rw-r--r--exercises/4.1-2/max_subarray_test.go43
2 files changed, 93 insertions, 1 deletions
diff --git a/0x01/README.md b/0x01/README.md
index 38bed54..ec5a526 100644
--- a/0x01/README.md
+++ b/0x01/README.md
@@ -310,7 +310,27 @@ properties.
1. Exercise 4.1-2 from the textbook (10 marks)
- What does `FIND-MAXIMUM-SUBARRAY` return when all elements of `A` are negative?
+ Write pseudocode for the brute-force method of solving the maximum-subarray
+ problem. Your procedure should run in `theta(n^2)` time.
+
+ The following brute force solution uses a nested loop that yields a worst case
+ of `n^2` iterations.
+
+ ```
+ FIND-MAXIMUM-SUBARRAY(A,low,high)
+ l = low
+ r = high
+ total = -1
+ for i = low to high
+ sum = 0
+ for j = i to high
+ sum = sum + A[j]
+ if sum > total
+ total = sum
+ l = i
+ r = j
+ return l, r, total
+ ```
1. Exercise 4.2-1 from the textbook (5 marks)
@@ -323,6 +343,35 @@ properties.
Show your work.
+ ```plaintext
+ Strassens algorithm:
+
+ n
+ cij = sigma ai*k * bkj
+ k=1
+
+ c11 = a11 * b11 + a12 * b21
+ c12 = a11 * b12 + a12 * b22
+ c21 = a21 * b11 + a22 * b21
+ c22 = a21 * b12 + a22 * b22
+
+ A = |a11 a12| B = |b11 b12|
+ |a21 a22| |b21 b22|
+ A = |1 3| B = |6 8|
+ |7 5| |4 2|
+
+ c11 = (1 * 6) + (3 * 4) = 18
+ c12 = (1 * 8) + (3 * 2) = 14
+ c21 = (7 * 6) + (5 * 4) = 62
+ c22 = (7 * 8) + (5 * 2) = 66
+
+ |c11 c12|
+ |c21 c22|
+
+ |18 14|
+ |62 66|
+ ```
+
1. Exercise 4.3-2 from the textbook (10 marks)
Show that the solution of `T(n) = T([n/2]) + 1` is `O(lg n)`
diff --git a/exercises/4.1-2/max_subarray_test.go b/exercises/4.1-2/max_subarray_test.go
new file mode 100644
index 0000000..920a3fb
--- /dev/null
+++ b/exercises/4.1-2/max_subarray_test.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "fmt"
+ "testing"
+)
+
+func MaxSubArray(a []int, low int, high int) (int, int, int) {
+ left := low
+ right := high
+ sum := -1
+
+ for i := low; i < high; i++ {
+ tempSum := 0
+ for j := i; j < high; j++ {
+ tempSum = tempSum + a[j]
+ if tempSum > sum {
+ sum = tempSum
+ left = i
+ right = j
+ }
+ }
+ }
+ return left, right, sum
+}
+
+func TestMergeSort(t *testing.T) {
+ t.Run("", func(t *testing.T) {
+ items := []int{100, 113, 110, 85, 105, 102, 86, 63, 81, 101, 94, 106, 101, 79, 94, 90, 97}
+ l, r, total := MaxSubArray(items, 0, len(items))
+
+ fmt.Println(l, r, total)
+ if l != 0 {
+ t.Errorf("Expected: %v, Got: %v", 0, l)
+ }
+ if r != 16 {
+ t.Errorf("Expected: %v, Got: %v", 16, r)
+ }
+ if total != 1607 {
+ t.Errorf("Expected: %v, Got: %v", 1607, total)
+ }
+ })
+}