leetCode练习(122)

题目:Best Time to Buy and Sell Stock II

难度:medium

问题描述:

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

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

解题思路:

使用Greedy 贪婪算法,只要后一项比前一项大,就买入并于后一项卖出。

代码如下:

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices==null||prices.length<2){
        	return 0;
        }
        int temp=prices[0];
        int pre;
        int sum=0;
        for(int i=0;itemp){
        		sum+=(pre-temp);
        		temp=pre;
        	}else{
        		temp=pre;
        	}
        }
        return sum;
    }
}

你可能感兴趣的:(leetCode)