首页 > 代码库 > [LeetCode]Best Time to Buy and Sell Stock II

[LeetCode]Best Time to Buy and Sell Stock II

题目:给定一个整形数组,表示股票走势,股票可以买入卖出任意次,求可以攒到的最大利润

算法:相当于对股票上升走势求和

例如:股票走势:1,1,3,2,5,7,1,3,2,0,则最大利润为(3-1)+(5-2)+(7-5)+(3-1)=9


public class Solution {
    public int maxProfit(int[] prices) {
	    	if (0 == prices.length) {
	    		// Empty array
	    		return 0;
	    	}
	    	
	        int maxProfile = 0;
	        int sellIn = prices[0];
	        for (int i=1; i<prices.length; ++i) {
	        	if (prices[i] > sellIn) {
	        		maxProfile += (prices[i]-sellIn);
	        		sellIn = prices[i];
	        	} else {
	        		sellIn = prices[i];
	        	}
	        }
	        return maxProfile;
	    }
}