ALGO AND DS
2 flashcards · Computer Science · by Kshitij Sabale
167. Two Sum II - Input array is sorted Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
class Solution { public: int longestOnes(vector<int>& A, int k) { int n = A.size(); vector<int> preA(n+1,0); for(int i=1;i<=n;i++) { preA[i] = A[i-1] + preA[i-1] ; } // for(int i=0;i<=n;i++) // cout<<preA[i]<<" "; // cout<<"\n"; int l =0,r=n,mid,ans=0; while(l<=r) { mid = l+(r-l)/2 ; int flag =0; for(int i=0;i<=n-mid;i++) { // cout<<preA[i+mid]<<" "<<preA[i]<<" "<<i+mid<<" "<<i<<"\n"; if(preA[i+mid]-preA[i]>=mid-k) { flag=1;break; } } if(flag) { ans = mid ; // cout<<mid<<" "<<l<<" "<<r<<"\n"; l…