Answer to Question #220198 in C++ for Catalina Bedoya

Question #220198

Flying fish can leap above or dive under the surface of the water a certain distance. You re given an array gain where gain[i] is the net gain in altitude between point i and point i+1 (please see examples). The fish always start at the water surface (altitude = 0). Return the highest altitude that the fish can reach.

Eg1:

Input: gain = {0, -5, 1, 5, 0, -7}

Output: {3, 1} or {4, 1}

Explanation: The fish start with altitude = 0, then dive -5 (altitude = 0 + (-5) = -5), then emerge 1 (altitude = -5 + 1 = -4), then emerge 5 (altitude = -4 + 5 = 1), then keep the same 0 (altitude = 1 + 0 = 1), then dive -7 (altitude = 1 + (-7) = -6).

Overall, the altitudes are {0, -5, -4, 1, 1, -6}. The highest is 1 at 3rd and 4th point.

Eg2:

Input: gain = {-4, -3, -2, -1, 4, 3, 2}

Output: {0, 0}

Explanation: The altitudes are {0, -4, -7, -9, -10, -6, -3, -1}. The highest is 0.

vector<int> flappyFish(vector<int> gain){
        
}




1
Expert's answer
2021-07-24T07:04:16-0400
#include<iostream>
#include<vector>
#include <algorithm>
#include<numeric>
using namespace std;


int main(){
		vector<int>output;
	vector<int>input {-4, -3, -2, -1, 4, 3, 2}; //Replace {-4, -3, -2, -1, 4, 3, 2} with {0, -5, 1, 5, 0, -7} to test
	if(input.at(0) != 0){
		output.push_back(0);
	}
	
int number=0;


	for(auto y = 0; y<input.size(); y++){
		
			number += input[y];
		
			output.push_back(number);
	}
	int max = *max_element(output.begin(), output.end());
     
	for(auto x=0; x<output.size()-1; x++){
		if(output[x] ==max){
			cout<<"{"<<x<<", "<<max<<"}" ;
		}
	}
    
	 
      
      
    
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS