Best Time to Buy and Sell Stock I

题意:

Say you have an array for which the ith element is the price of a given stock on day i.

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

Example 1:

Input: [7, 1, 5, 3, 6, 4] Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1] Output: 0

In this case, no transaction is done, i.e. max profit = 0.

method

动态规划法:从前向后遍历数组,记录当前出现过的最低价格,作为买入价格,并计算以当天价格出售的收益,作为可能的最大收益,整个遍历过程中,出现过的最大收益就是所求。 思考过程: dp[i]指的是当前股票买入的极小值,maxPro交易最大的利润。 <p>Input: [7, 1, 5, 3, 6, 4]时<p/> <p>当i = 0时, dp[0] = 7, maxpro[0] = 0;</p> <p>当i = 1时, dp[1] = min{dp[0],1} = 1, maxpro[1] = max{maxpro[0],1-7} = 0;<p/> <p>当i = 2时,dp[2] = min{dp[1],5} = 1, maxpro[2] = max{maxpro[1],5-1} = 4;<p/> <p>当i = 3时,dp[3] = min{dp[1],5} = 1, maxpro[3] = max{maxpro[2],5-1} = 4;<p/> <p>…………………以此类推<p/> <p>当i= n时,dp[n] = min{dp[n-1],prices[n]} = 1, maxpro[n] = max{maxpro[n-1],prices[n]-dp[n-1]};<p/>

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length < 2) return 0;
        
        int maxProfit = 0;
        int curMin = prices[0];
        
        for (int i = 1; i < prices.length; i++) {
            curMin = Math.min(curMin, prices[i]);
            maxProfit = Math.max(maxProfit, prices[i] - curMin);
        }
        
        return maxProfit;
    }
}

House Robber

题意

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

思路

这道题的本质相当于在一列数组中取出一个或多个不相邻数,使其和最大。 这是一道动态规划问题。 我们维护一个一位数组dp,其中dp[i]表示到i位置时不相邻数能形成的最大和。 状态转移方程:

dp[0] = num[0] (当i=0时)

dp[1] = max(num[0], num[1]) (当i=1时)

dp[i] = max(num[i] + dp[i - 2], dp[i - 1]) (当i !=0 and i != 1时)

public class Solution {
     public int rob(int[] nums) {
        if(nums.length<=0){
        	return 0;
        }
        if(nums.length == 1){
        	return nums[0];
        }
        
        int[] dp = new int[nums.length];
        dp[0] = nums[0];      //动态规划   i=0;

		dp[1] = Math.max(nums[0], nums[1]); //动态规划 i= 1

        for (int i = 2; i < nums.length; i++) {
			dp[i] = Math.max(nums[i]+dp[i-2], dp[i-1]);  //动态规划 i>1

		}
        return dp[nums.length-1];
    }
}