Showing posts with label Facebook. Show all posts
Showing posts with label Facebook. Show all posts
 

Continuous Subarray Sum

Given an integer array, find a continuous subarray where the sum of numbers is the biggest. Your code should return the index of the first number and the index of the last number. (If their are duplicate answer, return the minimum one in lexicographical order)
Example 1:
Input: [-3, 1, 3, -3, 4]
Output: [1, 4]
Example 2:
Input: [0, 1, 0, 1]
Output: [0, 3]
Explanation: The minimum one in lexicographical order.
Method: We will extend kadane's algorithm to solve this problem.
vector continuousSubarraySum(vector &A) {
    int max_sum = A[0], sum = 0, first = 0, last = 0;
    for(int i=0; i < A.size(); i++) {
        if(sum >= 0) {
            sum += A[i];
        } else {
            sum = A[i];
            first = i;
        }
        if(sum > max_sum) {
            max_sum = sum;
            last = i;
        }
    }
    return vector{first, last};
}
Time Complexity: O(n)
,  

Given a string of number. Calculate maximum value using ‘+’ or ‘*’ sign between two numbers in a string

Problem: Given a string of numbers, write a program to find the maximum value from the string, you can add a ‘+’ or ‘*’ sign between any two numbers.

For example:
Input: s = "123401"
Output: ((((1 + 2) * 3) * 4) + 0) + 1) = 37
In above manner we get maximum value.

Input: s = "781"
Output: ((7 * 8) + 1) = 57
In above manner we get maximum value.
Method 1: The idea here is to parse through the input one number at a time and if the number is 0 or 1 then use + else use * .
  • n * 0 = 0 but n + 0 = n, which is greater 
  • n * 1 = n but n + 1 = n + 1, which is greater 
Following is c++ implementation of the idea.
#include <bits/stdc++.h>
using namespace std;

/* function to get maximum value from string */
int maxVal(string s)
{
    /* store the first number in ans */
    int ans = (s[0] - '0');

    /* traversing the string */
    for(int i = 1; i < s.length(); i++)
    {
        /* if s[i] = 0 || s[i] = 1 || s[i-1] = 0 || s[i-1] = 1, we add */
        if((s[i]-'0') == 0 || (s[i]-'0') == 1 || (s[i - 1]-'0') == 1 || (s[i - 1]-'0') == 0)
        {
            ans += (s[i] - '0');
        }
        else
        {
            /* otherwise use * */
            ans *= (s[i] - '0');
        }
    }

    return ans;
}

/* driver function */
int main()
{
    string s = "123401";
    cout<<maxVal(s);   

    return 0;
}
Output:
37
Time Complexity: O(n)