leetcode [#122]

目录

题目

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


解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Solution {
public int maxProfit(int[] prices) {
int N = prices.length;
if(prices == null || N == 0) return 0;

int max = 0;
for(int i = 0; i < N -1; i++){
if(prices[i+1] > prices[i]){
max += (prices[i+1] - prices[i]);
}
}
return max;
}
}

注意事项

  1. 题目描述可以多次买入卖出,那自然也可以当天同时有买入和卖出。
  2. 要总获益最大,只要保证每组“买入卖出”都有收益,且有尽量多组“买入卖出”。所以遍历一遍,只要后一个元素比前一个元素大,就做“买入卖出”。