Question

Decrease-by-Half Algorithm We can solve the same problem using a decrease-by-half algorithm. This algorithm is based on the fWe can use a greedy algorithm to decide how far to the left to include: starting at the middle, move backward one index at a

Convert the pseudocode into a C++ function

Decrease-by-Half Algorithm We can solve the same problem using a decrease-by-half algorithm. This algorithm is based on the following ideas: In the base case, n 1 and the only possible solution is b 0, e 1 In the general case, divide V into a left and rnight half; then the maximum subarray can be in one of three places: o entirely in the left half; o entirely in the right half; or o starting in the left half and ending in the night half (cxossing the midpoint) The "entirely in2 cases can be handled with recursion; we can use a helper sub-algorithm to handle the "crossing" case. The overall optimal solution is the best of these three solutions. . maximum subarray dbh (V) return maximum subarray_recurse (V, 0, n) maximum subarray recurse (V, low, high): if low -high: return (low, low+1) middlelow+high) / 2 entirely left = maximum subarray recurse (v, 1 w, miadle) entirely right - maximum subarray recurse (Vv, middle + 1, high) crossing maximum subarray_crossing (V, low, middle, high) return (whichever of entirely left, entirely right, and crossina have the greatest sum) The sub-algorithm to find the maximum crossing subarray is based on these ideas: By definition we know that this subarray must include at least one element in the left half, and at least one element in the right half »
We can use a greedy algorithm to decide how far to the left to include: starting at the middle, move backward one index at a time, keeping track of the sum of all the elements we've visited. The best index to start with is whichever one has the largest sum. Likewise, we can use a greedy algonthm to decide how far to the right to include: starting at the middle, move forward one index at a time, keeping track of sums, and choosing whichever element maximizes the sum on the right side. maximum subarray crossing (V, low, middle, high: left-sum = right-sum = negative infinity f r i from middle down t 1 w : sum += v[i] if sum > left_sum: left sum sum sum O f r i from middle + 1 t high: umV[i] if sum > right sum: right sum surm return (b, e) This algorithm uses the idea of negative infinity, which exists in pseudocode, but not in the C++ programming language. Devising a way to implement this part of the algonthm is part of the project. You will probably need to wite helper functions to implement this algorithm; this is expected and totally fine. In the maximum subarray_crossing algorithm, each of the for loops takes O(n) time, and the rest of the algorithm takes 1) time, so the crossing sub-algoithm takes O(n) time. The time complexity of the entire maximumsubarray_recurse algorithm corresponds to a recurrence like T(n) = 2T(n/2)-O(n) so, bv the master theorem, and like merge sort, the time complexity ofmaximum subarray exh is O(n logn).
0 0
Add a comment Improve this question Transcribed image text
Answer #1

//C++ program

#include <iostream>
#include <limits.h>
using namespace std;  
   
int max(int a, int b) { return (a > b)? a : b; }
int maxCrossingSum(int arr[], int l, int m, int h)
{
int sum = 0;
int left_sum = INT_MIN;
for (int i = m; i >= l; i--)
{
sum = sum + arr[i];
if (sum > left_sum)
left_sum = sum;
}
sum = 0;
int right_sum = INT_MIN;
for (int i = m+1; i <= h; i++)
{
sum = sum + arr[i];
if (sum > right_sum)
right_sum = sum;
}
  
return left_sum + right_sum;
}
  
int maxSubArraySum(int arr[], int l, int h)
{
if (l == h)
return arr[l];
  
int m = (l + h)/2;
  
return max(maxSubArraySum(arr, l, m), max(maxSubArraySum(arr, m+1, h),
maxCrossingSum(arr, l, m, h)));
}

int main()
{
int arr[] = {-2, -5, 6, -2, -3, 1, 5, -6};
int n = sizeof(arr)/sizeof(arr[0]);
  
cout<<"Maximum contiguous sum is : "<<maxSubArraySum(arr, 0, n-1);

return 0;
}
//sample output

C:\Users\IshuManish\Documents\ maxsubarraysum.exe Maximum contiguous sum is ? Process exited after 0.06511 seconds with retur

Add a comment
Know the answer?
Add Answer to:
Decrease-by-Half Algorithm We can solve the same problem using a decrease-by-half algorithm. This...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • JAVA For the code in which I implemented most of the quick select algorithm. Quick select...

    JAVA For the code in which I implemented most of the quick select algorithm. Quick select is a O(n) time algorithm to find the nth smallest value in an (unordered list). The following recursive algorithm finds thenth smallest element with an index bewtween left and right in list: Code: Integer QuickSelect(list, left, right, n) { if left = right // If we only have one index available return list[left] // return the element at that index endif pivotIndex ⇐ partition(list,...

  • ALGORITHM PROBLEM: A) Significant Inversions: We are given a sequence of n arbitrary but distinct real...

    ALGORITHM PROBLEM: A) Significant Inversions: We are given a sequence of n arbitrary but distinct real numbers <a1 , a2 ,..., an>. We define a significant inversion to be a pair i < j such that ai > 2 aj . Design and analyze an O(n log n) time algorithm to count the number of significant inversions in the given sequence. [Hint: Use divide-&-conquer. Do the “combine” step carefully] B) The Maximum-Sum Monotone Sub-Array Problem: Input: An array A[1..n] of...

  • The binary search algorithm from Chapter 9 is a very efficient algorithm for searching an ordered...

    The binary search algorithm from Chapter 9 is a very efficient algorithm for searching an ordered list. The algorithm (in pseudocode) is as follows: highIndex - the maximum index of the part of the list being searched lowIndex - the minimum index of the part of the list being searched target -- the item being searched for //look in the middle middleIndex = (highIndex + lowIndex) / 2 if the list element at the middleIndex is the target return the...

  • Modify the sorts (selection sort, insertion sort, bubble sort, quick sort, and merge sort) by adding code to each to tally the total number of comparisons and total execution time of each algorithm. E...

    Modify the sorts (selection sort, insertion sort, bubble sort, quick sort, and merge sort) by adding code to each to tally the total number of comparisons and total execution time of each algorithm. Execute the sort algorithms against the same list, recording information for the total number of comparisons and total execution time for each algorithm. Try several different lists, including at least one that is already in sorted order. ---------------------------------------------------------------------------------------------------------------- /** * Sorting demonstrates sorting and searching on an...

  • Let's say you are given a sequence of distinct positive numbers. We want to find a...

    Let's say you are given a sequence of distinct positive numbers. We want to find a subsequence with the maximum possible sum, with the restriction that we are not allowed to take three consecutive elements from the original sequence. For example, for input 1, 6, 5, 2, 7, 9, 3, 4, the subsequence with the maximum possible sum is 6, 5, 7, 9, 4 (we have two pairs of consecutive elements 6, 5 and 7, 9 but not three consecutive...

  • 1. Please write a Divide-and-Conquer Java algorithm solving the following problem: Given an "almost sorted" array...

    1. Please write a Divide-and-Conquer Java algorithm solving the following problem: Given an "almost sorted" array of distinct integers, and an integer x, return the index of x in the array. If the element x is not present in the array, return -1. "Almost sorted" means the following. Assume you had a sorted array A[0…N], and then split it into two pieces A[0…M] and A[M+1…N], and move the second piece upfront to get the following: A[M+1]…A[N]A[0]…A[M]. Thus, the "almost sorted"...

  • I am using xcode Use the following ideas to develop a nonrecursive, linear-time algorithm for the...

    I am using xcode Use the following ideas to develop a nonrecursive, linear-time algorithm for the maximum-subarray problem. Start at the left end of the array, and progress toward the right, keeping track of the maximum subarray seen so far. Knowing a maximum subarray of A[1..j], extend the answer to find a maximum subarray ending at index j + 1 by using the following observation: a maximum subarray of A[1..j + 1] is either a maximum subarray of A[1..j] or...

  • C. 7. True/False Questions. (2 points each) a. Applying Horner's Rule, an n-degree polynomial can be...

    C. 7. True/False Questions. (2 points each) a. Applying Horner's Rule, an n-degree polynomial can be evaluated at a given point using only n multiplications and n additions. b. Quick Sort and Merge Sort are comparison-based sorting algorithms. Heap Sort and Distribution Counting Sort are not comparison-based sorting algorithms. An AVL tree applies four types of rotations: RIGHT, LEFT, RIGHT-LEFT, and LEFT-RIGHT. d. When an AVL tree's left sub-tree is left-heavy, a LEFT rotation is needed. e. When an AVL...

  • I need help In the lecture you got acquainted with the median algorithm, which calculates the median of an unsorted array with n∈N elements in O (n). But the algorithm can actually do much more: it is...

    I need help In the lecture you got acquainted with the median algorithm, which calculates the median of an unsorted array with n∈N elements in O (n). But the algorithm can actually do much more: it is not limited to finding only the median, but can generally find the ith element with 0≤i <n. Implement this generic version of the median algorithm by creating a class selector in the ads.set2.select package and implementing the following method: /** * Returns the...

  • can you please solve this CORRECTLY? Exercise 4 - Shortest path (25 pts) Using Dijkstra's algorithm,...

    can you please solve this CORRECTLY? Exercise 4 - Shortest path (25 pts) Using Dijkstra's algorithm, find the shortest path from A to E in the following weighted graph: a- Once done, indicate the sequence (min distance, previous node) for nodes D and E. (15pts) b- Below is a high-level code for Dijkstra's algorithm. The variables used in the code are self-explanatory. Clearly explain why its running time (when we use a min-heap to store the values min distance of...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT