LeetCode simple questions (four)

Topic one:

Given an array, which i-th element is a given stock i-day prices.

Design an algorithm to compute the maximum profit you can get. You can close more deals (buy and sell a stock) as much as possible.

Note: You can not simultaneously involved in multiple transactions (you must sell before buying shares again before the fall).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Day 2 (= 1 stock price), when buying, on day 3 (stock price = 5) when sold, this transaction can profit = 5-1 = 4.
  Then, on day 4 (stock price = 3) When buying on day 5 (stock price = 6), when sold, this transaction can profit = 6-3 = 3.

 

method one:

1. Violence Act , for this to solve the optimization problem, there must be a way of thinking --- recursion , does not seem to start with, recursion can often help us solve;

2, constructor recursion, recursion is not necessarily the original recursive function , such as arrays, you can recursively from the first, one more parameters;

3, calculate (int [] nums, int s), recursive outlet: if (s> = nums.length) return 0;

4, violent method, starting from the first element to traverse , for (int i = s, i <nums.length; i ++), for (int j = i + 1; j <nums.lenght; j ++) profit = calculate (nums, j + 1) + nums [j] = nums [i];

 

Specific code:

class Solution {
    public int maxProfit(int[] prices) {
        
        return calculate(prices, 0);
    }
public int calculate(int[] prices,int s) { if(s>=prices.length) return 0; int max=0; for(int i=s;i<prices.length;i++) { int MaxProfit=0; for(int j=i+1;j<prices.length;j++) { if(prices[i]<prices[j]) { int profit=calculate(prices, j+1)+prices[j]-prices[i]; if(profit>MaxProfit) MaxProfit=profit; } } if(MaxProfit>max) max=MaxProfit; } return max; } }

 

Guess you like

Origin www.cnblogs.com/Optimism/p/11441646.html