Let A = (A1, A2, A3,.....Ai) be defined as a sequence containing positive and negative integer numbers.
A substring is defined as (An, An+1,.....Am) where 1 <= n < m <= i.
Now, the weight of the substring is the sum of all its elements.
Showing your algorithms and proper working:
1) Does there exist a substring with no weight or zero
weight?
2) Please list the substring which contains the maximum weight
found in the sequence.
Part 1 :
Algorithm :
func (A) :
Let A be an input Array
1.Run loop i from 0 to leangth of Array A
2.Initialize sum=0
3.Run loop j from i to length of Array A
4.Add element at jth index of A to sum
5. If sum ==0 then print "Substring exist" and come out of the
function 'func'.
6. End of j loop
7. End of i loop
8. print "No such substring exist"
Note=> I am adding python code so as to explain the algorithm in a better way and to show outputs as well.
Code and Outputs :
Output 2:
Part 2 :
Algorithm :
func (A) :
Let A be an input Array
1. Initialize max value as first element of Array A, index start as
0 and index end as 0
1.Run loop i from 0 to leangth of Array A
2.Initialize sum=0
3.Run loop j from i to length of Array A
4.Add element at jth index of A to sum
5. If sum is greter tha max value then make max=sum , starting
index 'start' = i and last index 'last' =j
6. End of j loop
7. End of i loop
8. print substring starting from index start to index end
Code and Outputs :
Output 2 :
Get Answers For Free
Most questions answered within 1 hours.