Leetcode_122_best time to buy and Sell the stock II

Source: Internet
Author: User

This article is in the study summary, welcome reprint but please indicate the origin: http://blog.csdn.net/pistolove/article/details/43155725



Say you have an array for which the ith element are the price of a given the

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


Ideas:

(1) for given an array, the value of the first element of the array corresponds to the first day of the stock, you can complete many transactions, but each transaction can only buy once and sell, for multiple exchanges can get the maximum profit. The enhanced edition of the title "best time to Buy and Sell".

(2) similar to the Sell stock, the maximum difference is also examined in the same question. It only examines the sum of the differences in the values of all adjacent and incremental elements in the array. As long as the value of the first I+1 day is greater than the value of day I, then you can buy, get profit (margin), traverse the entire array, obtain the sum of the difference between the sum is the total profit.

(3) The problem is relatively simple. I hope it will be of some help to you.


The algorithm code is implemented as follows:

	/**
	 * 
	 * @author liqq
	/public int maxprofit (int[] x) {
		if (x = null | | x.length <= 1)
			return 0;

		int min = x[0];
		int profit = 0;

		for (int i = 0; i < x.length i++) {
			if (min > X[i]) {
				min = x[i];
			} else {
				Profit = x[i]-min ;
				min = X[i];
			}
		return profit;
	}




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.