Algorithm of greedy algorithm for efficient interview

Source: Internet
Author: User
Tags array length diff
Properties: Optimal substructure. Greedy Choice Property: Global optimal solution can be obtained by local optimal solution
Greedy algorithm, sub-problem can determine the whole problem, and DP sub-problem can only affect the whole problem.
Title index: Jump Game 1. Given an array, each element value represents the number of steps currently available to go, and the minimum hop count Farest=max (Farest,i+a[i]) is reached.
best time to Buy and Sell Stock 2,3 2. The best time to buy and sell stocks, analyzed separately 1) can be done once.  2) Maximum benefit Maxprices=max (Maxprices,prices[i]) that can be traded multiple times; Ans=max (Ans,maxprices-prices[i]);
Longest Substring without repeating characters 3. Given a string (with a repeating character), the substring Max_len=max (Max_len,i-start) of the longest non-repeating character,//i-start for the current no repeating string length start=last[s[i]-' a ']=i;// Update at least position is the next position of the repeating character O (n) to resolve the Container with the most water 4. Maximum volume of water the container can fit
Real Title 1:

Given an array of non-negative integers, you is initially positioned at the first index of the array.

Each element of the array represents your maximum jump length is at that position.

Determine if you is able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.


Analysis: You choose the biggest every step of the way you can guarantee that you walk the most steps if the maximum number of steps can not reach that will not reach the class solution {Public:bool canjump (int a[], int n) {         if (0==n) return false;         int farestdistance=a[0];         int cur=0; For (cur;cur<n && cur<=farestdistance;cur++) {Farestdistance=max (farestdistance, cur+a[  CUR]);         Cur array subscript, also your current position if (farestdistance>=n-1) return true;     } return false; } };

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 Step from index 0 to 1 and then 3 steps to the last index.)


Selecting the longest number of steps guarantees a minimum number of times.

Class Solution {

Public

int jump (int a[], int n) {

if (0==n)

return 0;

int cur=0,next=0,maxdistance=-1,count=0;//initialization always goes wrong

while (true)

{

if (next>=n-1)//write maxdistance>=n-1 always [0] test Case Pass

return count;

for (Cur;cur<=next;++cur)

{

Maxdistance=max (Maxdistance,cur+a[cur]);//greedy algorithm, select the largest moving value in the range of cur to next, current number + The maximum value that the current position can move

}

Cur=next; A new starting point for the next step

Next=maxdistance; This step can go to the maximum value

count++;

}

}

};


Topic 2:


Say you had an array for which the ith element was the price of a given stock on day I.

If you were-permitted-to-complete at most one transaction (ie, buy one and sell one share of the stock), design an AL Gorithm to find the maximum profit.


Find the maximum profit, you can only make one trade

Analysis:

Greedy method, find the lowest and highest price of the day, low into the higher, note the lowest day to change the original price sequence into a differential sequence, the subject can also be done is the maximum m sub-segment and, M = 1.


i--version with maximum value


Class Solution {

Public

int Maxprofit (vector<int> &prices) {

if (prices.size () = = 0)

return 0;

int ans;//Maximum Spread

int Maxprices=prices[prices.size ()-1];

for (int i=prices.size () -1;i>=0;i--)

{

Maxprices=max (Maxprices,prices[i]);//After the first day, that is, the i+1 to the nth day of the greatest interest maxprices, that is, the maximum value of the finding curve

Ans=max (Ans,maxprices-prices[i]),//That is, i+1 to the nth day of the greatest interest maxprices minus the first day, that is, the maximum benefit of the day I; ANS is the most profitable day in front of me

}

return ans;

}

};

Minimum value for i++ version


Say you had an array for which the ith element was the price of a given stock on day I.

Design an algorithm to find the maximum profit. You could complete as many transactions as (ie, buy one and sell one share of the stock multiple times). However, engage in multiple transactions for the same time (ie, you must sell the stock before you buy again).


To find the maximum profit, you can make multiple trades without the maximum minimum value, as long as the trading can make money, I will trade.
Class Solution {public:     int maxprofit (vector<int> &prices) {        if (pric Es.size () ==0 | | Prices.size () ==1)             return 0;         int ans[prices.size ()-1];         int buypoint=0,sellpoint=prices.size ()-1;         ans[0]=0;         for (int i=0;i<prices.size () -1;i++)         {      &NBSP ;                 if (Prices[i+1]>=prices[i])           & nbsp {                sellpoint=i+1,                 buypoint=i;//first time forget            }             Else &nbs P           {              ans[i+1]=ans[i];/* If prices[i +1]<prIces[i], the best interests of the former i+1 days remain unchanged, while choosing the lowest point buy stock * *                 buypoint=i+1;            }             if (Sellpoint>=buypoint && Prices[i+1]>=prices[i]//First time write here also forgot              ans[i+1]=max (prices[sellpoint]- Prices[buypoint],ans[i]+prices[i+1]-prices[i]);        }         return ans[prices.size ()-1];    };

Simplified version: Analysis greedy method, low into the high out, all the positive price difference to add up. Turning the original price sequence into a differential sequence, the subject can also be the maximum m sub-segment and, M = array length. Code//Leetcode, best time to Buy and Sell Stock II//Time complexity O (n), Space complexity O (1) class Solution {Public:int Maxprofit (vector&     Lt;int> &prices) {int sum = 0;          for (int i = 1; i < prices.size (); i++) {int diff = prices[i]-prices[i-1];     if (diff > 0) sum + = diff;     } return sum; } };
Topic 3:
Longest Substring without repeating characters description Given A string, find the length of the longest Substring without Repeati ng characters. For example, the longest substring without repeating letters for "ABCABCBB" are "abc", which the length is 3. For "bbbbb" the longest substring are "B", with the length of 1.



Question 4:

Container with most water

Describe

Given n non-negative integers A1; A2; :::; An, where each represents a point at coordinate (i; ai). N verti-

Cal Lines is drawn such, the endpoints of line I was at (i; ai) and (i; 0). Find lines, which together

With X-axis forms a container, such that the container contains the most water.

Note:you may not slant the container



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.