LeetCode122. Best time to buy and sell Stocks II

Source: Internet
Author: User

Given an array, the first element of it is the price of the first day of a given stock.

Design an algorithm to calculate the maximum profit you can get. You can do as many trades as possible (buy and sell a stock).

Note: You cannot participate in multiple transactions at the same time (you must sell the prior stock before buying again).

Example 1:

Input: [7,1,5,3,6,4] Output: 7 explanation: Buy on the 2nd day (stock price = 1), Sell on the 3rd day (stock price = 5), the trade can get Profit = 5-1 = 4.    then, on the 4th day (stock price = 3) to buy, on the 5th day (stock price = 6) of the time to sell, the transaction can obtain Profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5] Output: 4 explanation: Buy on the 1th day (stock price = 1), Sell on the 5th day (stock price = 5), the trade can get Profit = 5-1 = 4.     Note that you cannot buy stocks on the 1th and 2nd days, and then sell them.    since this is part of a multiple transaction, you must sell the stock before you buy it again.

Example 3:

Input: [7,6,4,3,1] Output: 0 explanation: In this case, no transaction is completed, so the maximum profit is 0.
 class   solution { public  int  maxprofit (int  Span style= "COLOR: #000000" >[] prices) { int  result = 0;         int  tmp = 0;  for  (int  i = 1; i < prices.length; I            ++ = prices[i]-prices[i-1);  if  (tmp > 0        += tmp;     return   result; }}

LeetCode122. Best time to buy and sell Stocks II

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.