Best Time to Buy and Sell Stock II

来源:互联网 发布:网络状况调查报告交流 编辑:程序博客网 时间:2024/05/18 08:18


题目描述:Say you have an array for which the ith element is the price of a given stock on dayi.

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).


解题思路:在交易中,当股价小于曾经最大股价时,卖出股价,累加利润。

Java代码实现:

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

原题题目:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

0 0
原创粉丝点击