FoY
BAN USERThis is the solution to get the range. My code assumes there's no 0 in the range. I will work on that too. The code should be self-explanatory.
#include <iostream>
using namespace std;
int main (){
int arr[]={6,-7,8,-9,8,-7,6};
int arrSize = sizeof(arr)/sizeof(int);
int arrProduct=1;
for (int i=0;i<arrSize;i++){
arrProduct*=arr[i];
}
int LHSProduct=1;
int RHSProduct=arrProduct;
int largestProduct=0;
int startRange =0, endRange = 0;
for (int i=0;i<arrSize;i++){
LHSProduct*=arr[i];
RHSProduct/=arr[i];
largestProduct = (LHSProduct>largestProduct) ? (startRange=0,endRange=i,LHSProduct) : largestProduct;
largestProduct = (RHSProduct>largestProduct) ? (startRange=i,endRange=arrSize-1,RHSProduct) : largestProduct;
}
for (int i = startRange;i<=endRange;i++){
cout << arr[i] << ", ";
}
cout << endl;
return 0;
}
Works well.
#include <iostream>
using namespace std;
void makeCombinations(int**, int, int , int&);
int const TARGET=12;
int const ARR[]={2,4,6,8};
int const ARR_SIZE=4;
int main (){
int** combinations = new int*[ARR_SIZE];
for (int i=0;i<ARR_SIZE;i++){
combinations[i]=new int[3];
combinations[i][0]=ARR[i];
combinations[i][1]=ARR[i]*-1;
combinations[i][2]=0;
}
int ways=0;
makeCombinations(combinations,0,0,ways);
cout << ways << endl;
for (int i=0;i<ARR_SIZE;i++)
delete [] combinations[i];
delete [] combinations;
}
void makeCombinations(int** combinations,int depth,int sum, int& ways){
if (depth==ARR_SIZE){
if (sum==TARGET)
ways++;
return;
}
for (int i=0;i<3;i++)
makeCombinations(combinations,depth+1,sum+combinations[depth][i],ways);
}
Repgarycsroka, Backend Developer at Axiom Sources
Hi I’m Gary, an average 19 year old in a state college who sees life as an adventure.Provide ...
I think the question actually means you have to find *contiguous* numbers in the array that give the highest sum. That's what I get from it when he asks to find a "subsequence". Not to form one out of the elements.
- FoY January 26, 2014